开发者

Method syntax causing confusion

开发者 https://www.devze.com 2023-03-08 01:52 出处:网络
def current_user=(user) @current_user = user end def user_from_remember_token User.authenticate_with_salt(*remember_token)
def current_user=(user)
    @current_user = user
end

def user_from_remember_token
    User.authenticate_with_salt(*remember_token)
end

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

1) I'm mostl开发者_如何学Cy confused with def current_user=(user). What is the = for. I see that it's taking the user object as a parameter, but what is the point of the = sign.

2) Not sure why there is a * infront of remember_token. Can anyone explain this?

Thanks


The = at the end of the method name is a syntactic sugar used for methods that assign a value. Since parentheses are optional in Ruby, you can write foo.current_user = (bar) or foo.current_user = bar. Note that the latter looks more natural. Also note that you can use attr_writer :current_user.

You can also use ? and ! in method names in Ruby. By convention, the former indicates a boolean value to be returned, the latter indicates "dangerous" methods (e.g. that modify the object instead of returning a copy).

The * wraps whatever what passed to the method into an array. It works also when calling a method, then it unwraps an array.

The || is simply logical or; if the first operand evaluates to nil or false, the other will be returned. Often you may find foo ||= "bar", which means that foo will get the value of "bar", unless it has a value (foo = foo || "bar").

Ruby is a great language with lots of these kind of quirks. Rubyist is a page worth visiting.


current_user=(user) is a setter that allows you to do something.current_user = foo. The according getter would be current_user and look like

def current_user
  @current_user
end


The = sign before to current_user refer to attr_writer method.

It means

 def current_user=(user)
     @current_user = user
 end

For Ref:

http://www.rubyist.net/~slagell/ruby/accessors.html    
http://apidock.com/ruby/Module/attr_writer
http://ruby-doc.org/core/classes/Module.html
0

精彩评论

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