Ruby on Rails 3:控制器方法内的 Setters、Getters 和 self
我对 Rails 3 应用程序控制器或助手中 setter 和 getter 的可用性有点困惑。 为什么有人会在控制器方法(或模块)中使用 setter 和 getter,而不仅仅是实例变量。有人可以举个例子吗? 使用 setter 和 getter 是否明智?什么时候需要?
例如,Michael Hartl 的《Rubby on Rails 3 教程》,它说(第 347 页):
Module SessionsHelper
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= user_from_remember_token
end
为什么不首先使用 @current_user
。
我的第二个问题是控制器方法中 self 的含义是什么。 例如:
Class SessionsController < ApplicationController
def sign_in?
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
self.current_user= user
end
end
我知道 User 模型类中的 self 指的是用户本身 但是当它在控制器内部时它指的是什么呢? 有什么例子吗?
谢谢
Iam a little bit confused about the usability of setters and getters inside a Rails 3 application controller or helper.
Why would someone use the setters and getters in a controller method (or a module) and not just an instance variable. Can someone give an example?
Is it wise to use setters and getters? And when is it required?
For example, Rubby on Rails 3 Tutorial by Michael Hartl, it says (page 347):
Module SessionsHelper
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= user_from_remember_token
end
Why not just use @current_user
in the first place.
My second question is what is the meaning of self inside a controller method.
For example:
Class SessionsController < ApplicationController
def sign_in?
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
self.current_user= user
end
end
I know that self inside the User model Class refers to the user itself
But when it is inside a controller what does it refer to?
Any example?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在控制器内部,
self
指的是控制器本身。因此,当您说self.current_user = user
时,您正在控制器上调用current_user=
(如 SessionsHelper 模块中所定义,我假设已正确包含该模块)。由于某些原因,这种技术更加干净。
current_user
时计算user_from_remember_token
的结果,但返回实例变量@current_user
的缓存结果否则。current_user
。访问另一个对象上的实例变量很尴尬,因为这应该是内部状态(旨在通过上面的current_user
和current_user=
方法等方法进行修改)。Inside a controller,
self
refers to the controller itself. So when you sayself.current_user = user
, you are callingcurrent_user=
on the controller (as defined in the SessionsHelper module, which I assume is being properly included).This technique is somewhat cleaner for a few reasons.
user_from_remember_token
to be calculated the first timecurrent_user
is called, but a cached result from the instance variable@current_user
to be returned otherwise.current_user
to be called on the controller from some other object. Accessing instance variables on another object is awkward since this is supposed to be internal state (which is intended to be modified through methods like thecurrent_user
andcurrent_user=
methods above).