I was given this ruby code to overview. I am still new to ruby on rails. I come from a java background.
in User.rb:
def last_name=name
require 'debugger'; debugger
self[:last_name] = name
end
And told me that this is a setter method. They told me that this get executed in the “form” in this line:
<%= f.label :last_name%>
<%= f.text_field :last_name %>
Ok. Could somebody clarify how this ridiculous syntax can be valid?
1) An instance of the class “User” is never initialized. How is the method even called?
2) Where does the variable “name” comes from? what is the value of it? (the variable name is called nowhere else) And what does this syntax stand for? “def last_name=name” ?? Pass to the method a variable that has not been initialized? It is a short-cut for another syntax just to save typing 2 more symbols?
3) How can this method be called, in the form? I dont see a “User.last_name(“David”) or anything similar.
Could somebody clarify those piece of code please?
And please dont post links to tutorial or anything else. Just clarify this piece of code
The code you described:
..is used by the default rails template engine. It is view code.
1) A User instance is likely initialized and populated when the form is submitted.
The form action corresponds to an appropriate controller action, which likely accepts
:last_nameas a parameter. When you submit the form, the controller action probably instantiates the User instance. Without more code, however, I can’t be 100% certain this is the case with your application.2) The variable
namecomes from the argument accepted by thelast_namemethod.Perhaps, to help you understand the method, let’s rewrite it:
Either
last_name=('John Doe')orlast_name = 'John Doe'will execute this method.3) I think my previous descriptions should help you make sense of this..