T
Thiago Arrais
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 =3D FirstChild.new
fst.redefinable_method =3D> "This is the custom string for the FirstChild c=
lass"
snd =3D SecondChild.new
snd.redefinable_method =3D> "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
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 =3D FirstChild.new
fst.redefinable_method =3D> "This is the custom string for the FirstChild c=
lass"
snd =3D SecondChild.new
snd.redefinable_method =3D> "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