bigpotato
bigpotato

Reputation: 27527

Rails: current_user and sessions clarification

I'm currently reviewing sessions and I came across a pretty generic sessions controller I used before:

module SessionsHelper

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

def sign_out
    self.current_user = nil
    cookies[:remember_token] = nil
end

def signed_in?
    !current_user.nil?
end

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

def current_user=(user)
    @current_user = user
end


end

And I realized that I used current_user in the views many times. ex:

<% if current_user == @user %>
    <%= current_user.name %>
<% else %>
    This user is not you.
<% end %>
  1. However, I don't understand why current_user is accessible as if it is an instance variable. Isn't it a method? Why is it that I can treat it the same as @current_user and pull out attributes from it like current_user.name, current_user.age, etc.? I thought that was only possible for instance variables.

  2. In the first and second methods sign_in(user) and sign_out, what does self refer to? These are considered class methods right?

Upvotes: 3

Views: 2705

Answers (1)

cdesrosiers
cdesrosiers

Reputation: 8892

  1. current_user is indeed a method defined in SessionHelper that just happens to return a reference to its internal instance variable @current_user. Such a method is usually referred to as "reader". Because the returned value is a reference to @current_user, you can use that value as if it were the actual instance variable, hence current_user.name

  2. The use of self is necessary in the definition of those two methods because without it, ruby will assume that you want to assign to a new local variable called current_user inside of the method instead of calling the method current_user=() already defined inside the module. In this case self refers to the module itself.

Upvotes: 4

Related Questions