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

I'm a little confused about the convenience of using setters and getters inside a Rails 3 application controller or helper. Why does someone use setters and getters in a controller method (or module), and not just in an instance variable. Can someone give an example? Can I use setters and getters? And when is it necessary?

For example, in the Rubby on Rails 3 tutorial by Michael Hartl (p. 347):

SessionsHelper Module

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 does the value of self inside the controller method mean. For instance:

 Class SessionsController < ApplicationController def sign_in? cookies.permanent.signed[:remember_token] = [user.id, user.salt] self.current_user= user end end 

I know that the inside of the user model class itself refers to the user itself. But when it is inside the controller, what does this apply to? Any example?

thanks

+4
source share
1 answer

Inside the controller, self refers to the controller itself. Therefore, when you say self.current_user = user , you call current_user= on the controller (as defined in the SessionsHelper module, which I assume is correctly enabled).

This method is somewhat cleaner for several reasons.

  • It allows you to add additional logic when the current user is read or assigned if you need to do this at a later point in time. Using an instance variable directly does not give such an extension point.
  • It allows you to calculate the result of user_from_remember_token on the first call to current_user , but otherwise, the cached result from the @current_user instance variable will be returned.
  • It may be necessary for current_user called on the controller from some other object. Access to instance variables on another object is inconvenient because it must be an internal state (which must be changed using methods such as current_user and current_user= above).
+5
source

All Articles