开发者

Ruby on Rails 3: Setters and Getters and self inside a controller method

开发者 https://www.devze.com 2023-03-24 08:44 出处:网络
Iam a little bit confused about the usability of setters and getters inside a Rails 3 application controller or helper.

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= 开发者_如何学Cuser
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


Inside a controller, self refers to the controller itself. So when you say self.current_user = user, you are calling current_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.

  1. It lets you add additional logic when the current user is read or assigned if you need to do so at a later point in time. Using the instance variable directly provides no such extension point.
  2. It allows the result of user_from_remember_token to be calculated the first time current_user is called, but a cached result from the instance variable @current_user to be returned otherwise.
  3. It might be desirable for 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 the current_user and current_user= methods above).
0

精彩评论

暂无评论...
验证码 换一张
取 消