More concise code

I found this snippet in code called acts_as_authenticated. I thought
it interesting but hard to understand at first.

@current_user ||= (session[:user] && User.find_by_id(session[:user]))
|| :false

Now for some possible embarrassment.

@current_user should return a value unless it is nil.

If nil(false),
then @current_user is set to session[:user] if session[:user] &&
User.find_by_id return true

otherwise, @current_user becomes false

Am I even close?

Mike B.

On 26 Apr 2007, at 13:10, barjunk wrote:

I found this snippet in code called acts_as_authenticated. I thought
it interesting but hard to understand at first.

@current_user ||= (session[:user] && User.find_by_id(session[:user]))
|| :false

Now for some possible embarrassment.

@current_user should return a value unless it is nil.

Perhaps I’m misunderstanding what you’re saying here, but I think
it’s the opposite meaning. @current_user will be set to a new value
(returned by the right hand side of the expression) unless it is
already true. I.e. if it is false or nil it will be set to the RHS.
Remember x ||= y expands to x = x || y

If nil(false),
then @current_user is set to session[:user] if session[:user] &&
User.find_by_id return true

otherwise, @current_user becomes false

Am I even close?

Mike B.

Almost. I’m not sure what the first line of your pseudo code means,
but the second line is a little bit wrong. @current_user is set to
the result of User.find_by_id(session[:user]), not session[:user].

Here’s my expanded Ruby code interpretation:

unless @current_user #Unless we already have a user set
if session[:user] and User.find_by_id(session[:user]) #Test if we
have session user and id
@current_user = User.find_by_id(session[:user]) #If we do then
set user to id
else
@current_user = :false #other wise user is set to :false
end
end

Some irb might help with all the ||=, ||, && line noise:

irb(main):004:0> foo = nil
=> nil
irb(main):005:0> bar = true
=> true
irb(main):006:0> foo ||= bar
=> true
irb(main):007:0> “foo” || “bar”
=> “foo”
irb(main):008:0> “foo” && “bar”
=> “bar”

Alex G.

Bioinformatics Center
Kyoto University

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs