simas simas - 3 months ago 9
Ruby Question

Ruby on Rails tutorial if (user_id = session[:user_id])

I am following ruby on rails tutorial by Michael Hartl and I don't get how he's using assignment operator inside if condintion:

if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
end


Can someone please explain the logic behind it?

Answer

This is one of the syntactic sugar in Ruby.

Ruby allows you to assign variables in conditionals and returns the value

x = true #=> returns true

if (user_id = session[:user_id])
  @current_user ||= User.find_by(id: user_id)
end

is equivalent to

user_id = session[:user_id]
if user_id
  @current_user ||= User.find_by(id: user_id)
end

Saves you a line. In case, session[:user_id] is falsy, it assigns the false value to user_id and doesn't execute the block.

Comments