Ruby On Rails Lesson
Having discussed how to store the user’s remember token in a cookie for later use, we now need to learn how to retrieve the user on subsequent page views. Let’s look again at the sign_in function to see where we are:
Our focus now is the second line:
The purpose of this line is to create current_user, accessible in both controllers and views, which will allow constructions such as
The use of self is necessary in this context for the same essential reason noted in the discussion leading up to Listing 8.18: without self, Ruby would simply create a local variable called current_user.
To start writing the code for current_user, note that the line
is an assignment, which we must define. Ruby has a special syntax for defining such an assignment function, shown in Listing 8.20.
This might look confusing—most languages don’t let you use the equals sign in a method definition—but it simply defines a method current_user= expressly designed to handle assignment to current_user. In other words, the code
is automatically converted to
thereby invoking the current_user= method. Its one argument is the right-hand side of the assignment, in this case the user to be signed in. The one-line method body just sets an instance variable @current_user, effectively storing the user for later use.