Search code examples
ruby-on-railsruby-on-rails-3

Rails Tutorial Michael hartl. Chapter 8 sign_in method, Why have we used writer method?


In Michael Hartls rails tutorial , I came across the following code :

module SessionsHelper 
def current_user=(user)
  @current_user = user
 end

 def current_user  #get logged in user
  @current_user||=User.find_by_remember_token(:remember_token)
 end

 def sign_in(user)   #sign the user in by setting cookies
  cookies.permanent[:remember_token]= user.remember_token
  current_user = user
 end

 def signed_in?(user)   #check whether user signed in
  !current_user.nil?
 end

end

My SessionsController create action looks like this :

def create
 user = User.find_by_email(params[:session][:email])
 if user && user.authenticate(params[:session][:password])
  sign_in user   # sign the user in by setting cookies
 else
  flash.now[:error]= "Invalid email/password"
  render 'new'
 end
end

Why do we need a writer method

def current_user=(user)
in the SessionsHelper module ?

Can't we just assign the value of user to the @current_user variable directly in the

sign_in
method ? Can it be done like this:

module SessionsHelper 

 # Notice that there is no def current_user=(user) method.

 def current_user
  @current_user||=User.find_by_remember_token(:remember_token)
 end

 def sign_in(user)
  cookies.permanent[:remember_token]= user.remember_token
  @current_user = user   #set the current user directly withoout a writer method
 end

 def signed_in?(user)
  !current_user.nil?
 end

end

Solution

  • Sure you can do like that. But idea is to incapsulate instance variable and never assign it directly outside getter and setter methods and that's how ruby works. You actually cannot do SomeObject.@instanceVar=. you need setter for that.

    So if in future you will need to set current_user eather you have to use sign_in method or create new method which will be like exactly setter. So why not to use it?