In Michael Hartl’s tutorial he has a module SessionsHelper, which has a method called current_user= which accepts a parameter and assigns it to @current_user. He then invokes this in various other methods in his program using a line like current_user = User.first.
My question is how we know that the current_user= method is being called at all — it seems to me that what would actually be happening is a new variable called current_user is created on the spot, given the value of User.first, and then when the function closes that variable dies.
I also tested this simply by creating the following code:
def x= val
puts "method called"
end
x = 46
puts x
This code snippet simply prints 46 on the screen – the function x= is never called at all. So what is the current_user= method doing in Michael Hartl’s tutorial, and how does he cause that function to be called?
It’s because Ruby treat expressions that can be read as simple variable as simple variable. You can see it with this code:
This is the same case. Look:
Also remember that assignment functions (like the last one) can’t return any value, the return value will always be the last argument.