From: Phrogz Date: 2008-02-13T06:14:55+09:00 Subject: Re: How to add a instance variable through a mixin? On Feb 12, 12:54 pm, "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 #=> # #=> # #=> # #=> #