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 mostly 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 writefoo.current_user = (bar)orfoo.current_user = bar. Note that the latter looks more natural. Also note that you can useattr_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 tonilorfalse, the other will be returned. Often you may findfoo ||= "bar", which means thatfoowill 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.