public Method

Module.attr_initialize(*attrs)

defines a series of instance variables to be initialized when the class is initialized.

For instance, you could create the class Foo:

class Foo
  attr_initialize :bar, :baz
  attr_accessor   :bar, :baz
end

and initialize an instance of the class as follows:

Foo.new(1, 2)

which will create a new Foo object with #bar equal to 1 and #baz equal to 2.

Passing a different number of arguments to new than you passed to attr_initialize will result in an ArgumentError being thrown.

Source Code

# File merb/core_ext/module.rb, line 53
def attr_initialize(*attrs)
  define_method(:initialize) do |*passed|
    raise ArgumentError, "Wrong number of arguments" \
      unless attrs.size == passed.size

    attrs.each_with_index do |att, i|
      instance_variable_set("@#{att}", passed[i])
    end

    after_initialize if respond_to? :after_initialize
  end
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.