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

This is caching abilities.

a ||= 1  # a assign to 1
a ||= 50 # a is already assigned, a will not be assigned again

puts a
#=> 1

this is useful when u load current user from DB, if this is loaded prior, statement will not try to evaluate right part of equation, which DRY, therefore u can consider it as caching operator.

REF: http://railscasts.com/episodes/1-caching-with-instance-variables


First made popular in C, the binary operator shorthand, for example:

a += b      # and...
a ||= b

acts like:

a = a + b   # and ... note the short circuit difference ... 
a || a = b

The rearrangement for a more effective short circuit is a graceful way of dealing with a check for nil as it avoids the assignment altogether if it can. The assignment may have side effects. Just another example of seriously thoughtful design in Ruby.

See http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html for a more wordy explanation.


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

Tags:

Ruby

Operators