I'm working through the RoR tutorial by Michael Hartl. Here's some code from SessionsHelper:
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
def current_user?(user)
user == current_user
end
def signed_in?
!current_user.nil?
end
def sign_out
self.current_user = nil
cookies.delete(:remember_token)
end
end
There are a number of things I don't understand from this code.
- In the method
current_user?
, iscurrent_user
a variable or is it an invocation of the methodcurrent_user
?
I don't understand how to determine the value of current_user
in this context.
- In the method
current_user
,@current_user
is an instance variable. What is it an instance variable of (i.e. what class?)?
If you look under the sign_in(user)
method, you can see that self.current_user
is assigned the value of the object user
. But (assuming self is of the class UsersController because UsersController < ApplicationController
and in the definition of ApplicationController
there is a line that include SessionsHelper
) there is no definition of an instance variable current_user
for the self
object.
- How come in
current_user=
we use the@current_user
but incurrent_user?
we just usecurrent_user
?
I've done h the prerequisite searching on StackOverflow but haven't found a good explanation for all these differences. A big part of what I'm trying to learn is when to use @current_user
, current_user
, :current_user
. I'm most familiar with C, C++, PHP, Java, JavaScript. If there are analogues to these languages, it would help me understand better what's going on.