Phrogz
2/12/2008 9:13:00 PM
On Feb 12, 12:54 pm, "MrBana...@googlemail.com"
<MrBana...@googlemail.com> wrote:
> > If you mix the module in after some instances of MyClass have already
> > been created, do you want it to dynamically create the instance
> > variables in those instances?
>
> > If you mix the module in before some instances of MyClass have been
> > created, do you want it to run code each time a new instance is
> > created?
>
> I would be interested in both cases, but for my particularly case it s
> the second one.
Here's a way to do it:
module Rands
def self.included( klass )
# Modify existing instances
ObjectSpace.each_object( klass ){ |inst|
inst.initialize_rands
}
# Replace the initialization with your own
klass.class_eval{
# Beware name clashes
alias_method :init_pre_rand, :initialize
def initialize( *args )
init_pre_rand( *args )
initialize_rands
end
}
end
def initialize_rands
@foo = "%.2f" % rand
end
end
class Foo
def initialize( id )
@id = id
end
end
f1 = Foo.new( 1 )
f2 = Foo.new( 2 )
class Foo
include Rands
end
f3 = Foo.new( 3 )
f4 = Foo.new( 4 )
p f1, f2, f3, f4
#=> #<Foo:0x7ffa696c @id=1, @foo="0.92">
#=> #<Foo:0x7ffa691c @id=2, @foo="0.57">
#=> #<Foo:0x7ffa6908 @id=3, @foo="0.40">
#=> #<Foo:0x7ffa68cc @id=4, @foo="0.41">