ruby-on-rails - Ruby 中方法名与@的混淆
天蓬老师
天蓬老师 2017-04-22 09:00:26
0
3
538
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 又指的是什么?感觉有点混淆了,求解答。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
迷茫

@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_userthe return value after the call.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!