Ruby On Rails Lesson
We end our tour of Ruby with a complete class of our own, a User class that anticipates the User model coming up in Chapter 6.
So far we’ve entered class definitions at the console, but this quickly becomes tiresome; instead, create the file example_user.rb in your application root directory
and fill it with the contents of Listing 4.9.
Listing 4.9 Code for an example user.
There’s quite a bit going on here, so let’s take it step by step. The first line,
creates attribute accessors corresponding to a user’s name and email address. This creates ‘‘getter’’ and ‘‘setter’’ methods that allow us to retrieve (get) and assign (set) @name and @email instance variables, which were mentioned briefly in Section 2.2.2. In Rails, the principal importance of instance variables is that they are automatically available in the views, but in general they are used for variables that need to be available throughout a Ruby class. (We’ll have more to say about this in a moment.) Instance variables always begin with an @ sign, and are nil when undefined.
The first method, initialize, is special in Ruby: It’s the method called when we execute User.new. This particular initialize takes one argument, attributes: