Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 311
Simonas Avatar asked Nov 30 '25 03:11

Simonas


2 Answers

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.

like image 53
kiddorails Avatar answered Dec 01 '25 16:12

kiddorails


You are allowed to use the assignment operator in an if statement because an assignment is an expression. The result of the assignment expression is the value of what you are assigning.

In this case, if session[:user_id] is not nil or false, the result of the if branch will be called and user_id will be set to the result of session[:user_id]. If session[:user_id] is nil or false it will still be assigned to user_id but the logic inside the if will not evaluate.

like image 37
kcdragon Avatar answered Dec 01 '25 17:12

kcdragon