def current_user
@_current_user ||= session[:current_user_id] &&
User.find_by_id(session[:current_user_id])
end
Is @_current_user simply an id or a user object found by its id?
def current_user
@_current_user ||= session[:current_user_id] &&
User.find_by_id(session[:current_user_id])
end
Is @_current_user simply an id or a user object found by its id?
To answer your question directly: A user object found by its id or nil
if there is no :current_user_id
value in the session or if no user object exists for that id.
Basically, if @_current_user
is already set then it won't change it. Otherwise, then it checks if session[:current_user_id]
exists/is set, and if it is, by nature of the &&
operator, the right side is returned as the value of the expression. The right side basically looks up the user with that current_user_id
.
Even simpler: If @_current_user
isn't set yet, then if the session has a current_user_id
value, it sets @_current_user
to the User
object matching that user id.
If we assume session[:current_user_id]
is 5
, then the &&
operator with the User model will return the User instance:
> 5 && User.new(:name => 'Foo')
=> #<User name="Foo">
If both sides of the &&
operator are "truthy" (meaning neither undefined or false
), then the right-hand side value is returned by the &&
operator. So @_current_user
will be the User instance.