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
# Returns true if the user is logged in, false otherwise
def logged_in?
!current_user.nil?
end
# Logs out the current user
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
end
最后两个 def
中的 current_user
到底指的是什么?是上面定义的 current_user
方法吗?
而以上代码中的 @current_user
又指的是什么?感觉有点混淆了,求解答。
@current_user is an instance variable, current_user is a method in this module, and the last two methods calling current_user refer to calling the current_user method above. Instance methods in the same class can be called directly using the method name.
@current_user is a return value in the current_user method. The last two methods call the current_user method, which actually gets the instance variable @current_user.
@current_user is a variable of the global class, current_user is the method name, () can be omitted when calling the method in ruby, so beginners are easily confused, the value of @current_user is nil (the value initialized by @xxx is nil) or current_user returns value.
To compensate,
current_user
实际上代指current_user
这个方法返回的@current_user
实例变量。因为这里我们获得的是current_user
the return value after the call.