From: Robert Klemme Date: 2005-01-26T01:35:49+09:00 Subject: Re: Injecting methods from one class into another. "Robert Klemme" schrieb im Newsbeitrag news:35nafhF4of2saU1@individual.net... > > "George Moschovitis" schrieb im Newsbeitrag > news:1106667522.708436.185960@z14g2000cwz.googlegroups.com... > > > Object methods do not work in vacuum, they usually use instance > > > variables to reffer to the object's state, possibly changing it > > > (remember encapsulation ;-)?). How would you expect your > > > inject_method() deal with it? > > > > I thought Ruby promotes 'duck typing'. > > > > I would like to inject specific methods between specific classes. The > > destination class has all the instance variables needed to succesfully > > execute the method. > > And what about other methods that are used by a method? I think it's not > generally possible to move methods around. > > But maybe this trick helps: Should've read class Object def cast(target_class) copy = case target_class when Class; target_class.allocate when Module; dup.extend(target_class) else target_class.class.allocate end instance_variables.each do |var| copy.instance_variable_set(var, instance_variable_get(var)) end copy end end > Then you can create a tmp copy of an instance with all instance variables > copied but a different class. So you can do > foo.cast(Bar).bar_method_to_be_called(). > > Cheers > > robert >