I am in section 8.4.3 - Forgetting Users of the Rails Tutorial.
# app/helpers/session_helper.rb
module SessionsHelper
...
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
# Logs out the current user
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
...
end
In the current_user method we assign a user to the @current_user instance variable. I don't understand why we don't use that same instance variable in the log_out method (in that method current_user is not prepended with an @ symbol). Where does current_user come from then since it isn't passed in as an argument to that method?
forget(current_user)it is calling helpercurrent_user. Ruby methods default return last executed line. Socurrent_userhelper will return@current_userobject if user logged_id.@current_useris not set until you call thecurrent_usermethod. So in the scope of thelog_outmethod, you have to assume@current_userdoesn't exist until you run the method that creates it, which iscurrent_user.