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:
return “This is the default string returned when the method
def redefinable_method return self.class.redefinable_method end
class FirstChild < Parent
redefine “This is the custom string for the FirstChild class”
class SecondChild < Parent; end
fst = FirstChild.new
fst.redefinable_method => “This is the custom string for the FirstChild
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.
Is it possible to do that?
Can the client code (child classes) be made any simpler/shorter?