gpt4 book ai didi

ruby-on-rails - 了解 Ruby on Rails 中的类变量和方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:27 25 4
gpt4 key购买 nike

我是 Ruby 和 Ruby on Rails 的新手,来自类 C 语言的背景。
这是我在 application_controller.rb 文件中找到的一些代码:

def current_user
@current_user ||= Renter.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user

def authorize_user
redirect_to '/login' unless current_user
end

以下是我不明白的地方:
- 第4行,:current_user是调用current_user实例方法,还是直接访问@current_user实例变量?
- 第7行,current_user是调用current_user实例方法,还是直接访问@current_user实例变量?
- 在第 2 行,:user_id 是变量还是更像是用作键的字符串文字?有点像在 JavaScript 中,可以编写 session["user_id"] 来获取 session 对象的 user_id 属性。

最佳答案

类方法与此示例无关 - 此处未使用它们。

实例变量在获取/设置时永远不会调用方法。

虽然有时会发生相反的情况。为实例变量创建 getter/setter 方法是一种非常常见的模式,如此常见以至于 attr reader/writer/accessor helpers 在 ruby​​ 核心中定义。如果您编写 attr_accessor :foo,则 foo=foo 将获取/设置实例变量。

但默认情况下不会发生这种情况。

回答你的另一个问题:

符号:user_id以冒号开头,类似于字符串。符号和字符串之间的区别可能看起来很随意,但它是 Ruby 中的一个重要概念,在头脑中做出区分是个好主意。


回复您的评论:

第 4 行,helper_method :current_user 确实是 Rails 特有的东西,如果您愿意,可以将其视为“Rails 魔法”。实际上,这使您的 current_user 方法可从 View 中调用(而默认情况下它仅在 Controller 中可用)。 :current_user 是一个符号,用于引用current_user 方法。不一定要了解全部细节,知道 helper_method 采用与方法同名的符号并使该方法可用于 View 就足够了。据我所知,它只与 Rails Controller 有关。

在 Ruby 中使用引用方法名称的符号有些常见。这是一个更中间的概念。您可以在 send 中看到另一个示例:

def asd
return 0
end

class Foo
def instance_method_bar
return 0
end
def self.class_method_bar
return 0
end
end

# how the methods are typically called
asd
Foo.new.instance_method_bar
Foo.class_method_bar

# another way to call them, using send
send(:asd)
Foo.new.send(:instance_method_bar)
Foo.send(:class_method_bar)

我不推荐你使用 send 除非你需要,但希望它能让你更清楚 :current_user 是如何在 中使用的辅助方法

第 7 行是被调用的 current_user 方法。

关于ruby-on-rails - 了解 Ruby on Rails 中的类变量和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39282460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com