I'm following railstutorial by Michael Hartl. In chapter 8.2.2 he defines a variable @current_user
and a method current_user
.
app/helpers/sessions_helper.rb looks like this:
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
end
Hartl defines @current_user an instance variable (of User object I guess); How can @current_user be an instance variable if it is itself an instance of the User class?
The SessionsHelper
module is mixed into your controllers, so @current_user
will be set as an instance variable of the controller which is handling the current request (Rails creates a new controller instance to handle each request)