Home  >  Q&A  >  body text

ruby-on-rails - Ruby 中方法名与@的混淆

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 又指的是什么?感觉有点混淆了,求解答。

天蓬老师天蓬老师2712 days ago544

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-22 09:02:26

    @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.

    reply
    0
  • 迷茫

    迷茫2017-04-22 09:02:26

    @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.

    reply
    0
  • 黄舟

    黄舟2017-04-22 09:02:26

    To compensate, current_user实际上代指current_user这个方法返回的@current_user实例变量。因为这里我们获得的是current_userthe return value after the call.

    reply
    0
  • Cancelreply