Given the following class:
class Test
attr_accessor :name
end
When I create the object, I want to do the following:
t = Test
There is a general way of doing complex object initialization by passing a block with necessary actions. This block is evaluated in the context of the object to be initialized, so you have an easy access to all instance variables and methods.
Continuing your example, we can define this generic initializer:
class Test
attr_accessor :name
def initialize(&block)
instance_eval(&block)
end
end
and then pass it the appropriate code block:
t = Test.new { @name = 'name' }
or
t = Test.new do
self.name = 'name'
# Any other initialization code, if needed.
end
Note that this approach does not require adding much complexity
to the initialize method, per se.