Question

The famous tutorial uses self to assign user to an instance variable.

module SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.hash(remember_token))
    self.current_user = user
  end



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

Why wouldn't the following be valid? The book says this type of assignment would create a local variable.

module SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.hash(remember_token))
    @current_user = user
  end



  ###def current_user=(user)
 #   @current_user = user
  # end
# end
Was it helpful?

Solution

If you have @current_user = user in sign_in method then it should definitely work which is as good as calling the commented method current_user=. @current_user is not a local variable, it is an instance variable.

The book says this type of assignment would create a local variable.

Book is not talking about @current_user = user BUT about current_user = user (Notice without prefix @) which will set a local variable current_user and not call the instance method current_user=.

When you call self.current_user = user, then self is the explicit receiver so Ruby knows that current_user= is a method and not a local variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top