Why is there an assignment method needed when you can just use "=" (from the Hartl tutorial)?

I have a terrible understanding of understanding the assignment function that is required, as described in chapter 8.2.3 . Hartl tutorial.

As a context, it focuses on the second line of the following sign_in function:

  def sign_in(user) cookies.permanent[:remember_token] = user.remember_token self.current_user = user #<-- this line end 

Where does he mention, because its purpose, it should then be separately defined as

 def current_user=(user) @current_user = user end 

If the current_user= method current_user= explicitly designed to handle assignment before current_user . My perplexity:

  • Why is this even necessary? I thought simple = would allow you to assign things. For example user.email = hello@kitty.com

  • Also, when in the end it will be code redirect_to current_user , how does what belongs to SessionsController translate into a view controlled by UsersController ?

Thanks!!

+4
source share
1 answer

The reason is that it is necessary to avoid confusion (for the interpreter / virtual machine) between the method call and the assignment of a variable

 def foo # Two completely different things! bar = "baz" # assigns baz to local variable bar self.bar = "baz" # invokes the bar= method with parameter of baz end 

What happens is that it does two things, first calling the current_user= method with a custom object, and secondly setting it to @current_user (this is not a great example - you will probably end up doing a lot more in real life if you have to make the current_user= method, such as setting session variables).

secondly redirect_to current_user equivalent to redirect_to user_path(current_user) - see http://api.rubyonrails.org/classes/ActionController/Redirecting.html for more details that explains the different types of parameters that redirect_to can take. Note that this is a redirect, not a render, so here comes the second HTTP request.

+5
source

All Articles