From: Logan Capaldo Date: 2006-04-02T06:16:44+09:00 Subject: Re: Dynamic code generation On Apr 1, 2006, at 12:03 PM, Thiago Arrais wrote: > I have been trying to do some simple dynamic code generation in Ruby. > What I am specifically trying is to redefine a class level method on > the subclasses. I know I may achieve that by using a simple def, but I > would like come up with a simpler syntax, something like this: > > ---- > class Parent > def self.redefinable_method > return "This is the default string returned when the method > isn't redefined" > end > > def redefinable_method > return self.class.redefinable_method > end > end > > class FirstChild < Parent > redefine "This is the custom string for the FirstChild class" > end > > class SecondChild < Parent; end > > fst = FirstChild.new > fst.redefinable_method => "This is the custom string for the > FirstChild class" > > snd = SecondChild.new > snd.redefinable_method => "This is the default string returned when > the method isn't redefined" > ---- > > In this example you can see two points: (a) I am a total newbie, (b) > the method 'redefine' should be defined on the parent class, but I > don't have a clue on how it should be written. I have taken a look at > ActiveRecord's associations, but it seems like overkill to use the > exact same approach. > > Two questions: > > Is it possible to do that? > Can the client code (child classes) be made any simpler/shorter? > > Cheers, > > Thiago Arrais > This seems to be a solution looking for a problem class Parent def redefinable_method "This is the default string returned when the method isn't redefined" end end class FirstChild < Parent def redefinable_method "This is the custom string for the FirstChild class" end end class SecondChild < Parent; end I don;t see what you gain by meta-programming here