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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With