What does the initialize method in rails do

2020-05-21 09:38发布

问题:

I'm trying to wrap my head around the purpose of using the initialize method. In Hartl's tutorial, he uses the example..

def initialize(attributes = {})
   @name = attributes[:name]
   @email = attributes[:email]
end

Is initialize setting the instance variables @name and @email to the attributes, and if so why do we have the argument attributes = {}?

回答1:

Ruby uses the initialize method as an object's constructor. It is part of the Ruby language, not specific to the Rails framework. It is invoked when you instanstiate a new object such as:

@person = Person.new

Calling the new class level method on a Class allocates a type of that class, and then invokes the object's initialize method:

http://www.ruby-doc.org/core-1.9.3/Class.html#method-i-new

All objects have a default initialize method which accepts no parameters (you don't need to write one - you get it automagically). If you want your object to do something different in the initialize method, you need to define your own version of it.

In your example, you are passing a hash to the initialize method which can be used to set the default value of @name and @email.

You use this such as:

@person = Person.new({name: 'John Appleseed', email: 'john@some.net'})

The reason the initializer has a default value for attributes (attributes = {} sets the default value to an ampty hash - {}) is so that you can also call it without having to pass an argument. If you dont' specify an argument, then attributes will be an empty hash, and thus both @name and @email will be nil values as no value exists for those keys (:name and :email).