0

I am learning Rails from Michael Hartl's tutorial, but I am really confused about the SessionsHelper module. Not enough information is provided about the duplication of the current_user method. Could someone explain why there are two and what are their individual purposes?

module SessionsHelper

  def sign_in(user)
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
  end

  def current_user=(user)
    @current_user = user
  end

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

end

I understand the sign_in method would trigger the call to current_user=(user) but why the current_user method again? I understand the second method gets the user based on remember_token from the database, but I can't connect the dots regarding these.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Horse Voice
  • 8,138
  • 15
  • 69
  • 120

1 Answers1

2

current_user is the reader method and current_user= is the writer method for your attribute current_user. These two are separate methods, one would be used to read the value and other to write value of current_user.

EDIT

In your case, current_user= method means that set the value of instance variable @current_user equal to the passed value(user).

def current_user=(user)
    @current_user = user
end

current_user method means,

def current_user
    ## if @current_user = nil then   
    ## set @current_user = User.find_by_remember_token(cookies[:remember_token])
    ## else return @current_user

    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
end

sign_in method,

def sign_in(user)
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
end

sign_in method would be called as sign_in user from a controller.

Like Aaron mentioned in the comment, without self, Ruby would simply create a local variable called current_user which would be lost once sign_in method finishes execution.

But by saying, self.current_user = user the value of current_user would be preserved in the current instance(instance of controller in which you have included the module) of class.

For a better understanding of self refer to this Stackoverflow question on self

Community
  • 1
  • 1
Kirti Thorat
  • 52,578
  • 9
  • 101
  • 108
  • So current_user method just returns the @current_user variable thats pulled from the DB? Also could you explain what is the self method doing there in the sign_in method? I thought self was only used in models to refer to that record being pulled from the database. – Horse Voice Feb 28 '14 at 03:12
  • 2
    The `self.` is telling ruby to use the `current_user=` method on the instance of the class rather than making a new local variable called `current_user` and assigning the `user` to it only to have it go out of scope. – Aaron Feb 28 '14 at 03:13
  • @TazMan Check my updated answer. See if it clears your doubts. – Kirti Thorat Feb 28 '14 at 03:59