When do we use the "||=" operator in Rails ? What is its significance?

geeky_monster picture geeky_monster · Apr 17, 2011 · Viewed 49.9k times · Source

Possible Duplicate:
What does the operator ||= stands for in ruby?

I am confused with the usage of ||= operator in Rails. I couldn't locate anything useful on the web. Can anyone please guide me?

Do let me know if there are any weblinks that you are aware of.

I would like what the following statement means:

@_current_user ||= session[:current_user_id] &&
      User.find(session[:current_user_id])

Answer

Mike Lewis picture Mike Lewis · Apr 17, 2011

Lets break it down:

@_current_user ||= {SOMETHING}

This is saying, set @_current_user to {SOMETHING} if it is nil, false, or undefined. Otherwise set it to @_current_user, or in other words, do nothing. An expanded form:

@_current_user || @_current_user = {SOMETHING}

Ok, now onto the right side.

session[:current_user_id] &&
      User.find(session[:current_user_id])

You usually see && with boolean only values, however in Ruby you don't have to do that. The trick here is that if session[:current_user_id] is not nil, and User.find(session[:current_user_id]) is not nil, the expression will evaluate to User.find(session[:current_user_id]) otherwise nil.

So putting it all together in pseudo code:

if defined? @_current_user && @_current_user
  @_current_user = @_current_user
else
  if session[:current_user_id] && User.find(session[:current_user_id])
    @_current_user = User.find(session[:current_user_id])
  else
    @_current_user = nil
  end
end