Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2|
Lessons:-A User Class

A user Class

Here the attributes variable has a default value equal to the empty hash, so that we can define a user with no name or email address (recall from Section 4.3.3 that hashes return nil for nonexistent keys, so attributes[:name] will be nil if there is no :name key, and similarly for attributes[:email])

                    Finally, our class defines a method called formatted_email that uses the values of the assigned @name and @email variables to build up a nicely formatted version of the user’s email address using string interpolation (Section 4.2.2):

 

def   formatted  email
     "# { @ name }  <# { @email }>"
end

 

Because @name and @email are both instance variables (as indicated with the @ sign), they are automatically available in the formatted_email method. 

             Let’s fire up the console, require the example user code, and take our User class out for a spin:

 

Here the ’.’ is Unix for ‘‘current directory,’’ and ’./example_user’ tells Ruby to look for an example user file relative to that location. The subsequent code creates an empty example user and then fills in the name and email address by assigning directly to the corresponding attributes (assignments made possible by the attr_accessor line in Listing 4.9). When we write

 

example.name =   "Example User"

 

  Ruby is setting the @name variable to "Example User" (and similarly for the email attribute), which we then use in the formatted_email method. Recalling from Section 4.3.4 that we can omit the curly braces for final hash arguments, we can create another user by passing a hash to the initialize method to create a user with predefined attributes:

 

>>  user = User  .new(name:  "Michael Hartl",  email:  "mhartl@example.com")
=>  #<User:0x225167c  @email=  "mhartl@example.com",   @name="Michael Hartl">
>>  user .formatted  email
=>  "Michael Hartl   <mhartl@example.com>"

 

We will see starting in Chapter 7 that initializing objects using a hash argument is common in Rails applications. 

 
 
 
image
Pooja   Negi

Skills    Ruby On Rails

Qualifications :- High School - SSN high school, College/University - HNBGU, College/University - SRHU,
Location :-Ranipokhari,Rishikesh,Uttarakhand,India
Description:- Student
Explore
 

  Students (0)