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 %>
-
However, I don’t understand why
current_useris 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_userand pull out attributes from it likecurrent_user.name,current_user.age, etc.? I thought that was only possible for instance variables. -
In the first and second methods
sign_in(user)andsign_out, what doesselfrefer to? These are considered class methods right?
current_useris indeed a method defined inSessionHelperthat 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, hencecurrent_user.nameThe use of
selfis necessary in the definition of those two methods because without it, ruby will assume that you want to assign to a new local variable calledcurrent_userinside of the method instead of calling the methodcurrent_user=()already defined inside the module. In this caseselfrefers to the module itself.