开发者

Help on ruby methods with the same name

I am currently working through http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:current_user]1 and I am having trouble unde开发者_StackOverflow社区rstanding what the difference between the two current_user methods. In my other method sign_in there is a called to self.current_user but I am having trouble understanding which current_user is called and what the other current_user method is actually doing.

module SessionsHelper
  def sign_in(user)
    cookies.permanent.signed[:remember_token] = [user.id, user.salt]
    self.current_user = user
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    @current_user ||= user_from_remember_token
  end

  def signed_in?
    !current_user.nil?
  end

  private
    def user_from_remember_token
      # using the * makes us pass two values [id,salt]
      User.authenticate_with_salt(*remember_token)
    end

    def remember_token
      cookies.signed[:remember_token] || [nil,nil]
    end
end


The current_user= method is called when you assign to the current_user attribute of your object, and the current_user method is called when you don't.

So self.current_user = user calls current_user= while !current_user.nil? calls current_user.


The difference is that current_user= implements the equal operator. So when you do current_user = something, it is really calling current_user=(something).

As opposed to current_user, which is just a 'getter'.

I'd read this article on Ruby Accessors.


This is assignment method.

to be used like

obj.current_user= some_user_object calls following method.

  def current_user=(user)
    @current_user = user
  end

Following method returns the object current user. If @current_user is null it will assign the user object to it and return it.

some_user=obj.current_user calls following method.

  def current_user
    @current_user ||= user_from_remember_token
  end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜