From: Joel VanderWerf Date: 2009-07-07T03:39:54+09:00 Subject: Re: A define_method question Juston wrote: > I have a question about define_method, more specifically how to bend > it to my purpose. > > The problem I am trying to solve is I have an object "Action" which > basically carries out a static set of actions based off instance > variables. "Action" can also be modified by MANY "Modifier"s. A > "Modifier" just adds in a little bit of extra code that can changes an > "Action"s operations just a bit. (Example: Action with a Modifier to > email someone with a report, something I wouldn't want on every object > and don't want to lump into some sort if/else statement in Action) > > What I would like to be able to do is have an empty method > "Action.runModifiedCode" within the "Action" class that would allow me > to just inject the code right into "Action." This is easy enough to do > using define_method (or a mix-in) to override the mock method, but > this doesn't work when the "Action" has more than one "Modifier." > > Long winded story short, is there something that would allow me to > take the code from one object method and append to another object's > method? Are you sure mixins won't work? class Action def do_stuff super if defined? super puts "starting to do stuff" end end module M1 def do_stuff super if defined? super puts "M1 modifier" end end module M2 def do_stuff super if defined? super puts "M2 modifier" end end module M3 def do_stuff super if defined? super puts "M3 modifier" end end a = Action.new a.extend M1 a.extend M2 class Action include M3 # M3 is global for all instances of Action end a.do_stuff # ==> # M3 modifier # starting to do stuff # M1 modifier # M2 modifier -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407