Hey,
I want to realise some kind of virtual methods. I’ll explain this with
an example:
Let’s assume I’ve got a class called “Animal”. Every “Animal” instance
can have various attributes, which are not fix, they depend on the
annotations associated within the “animal” database table. So I could
create a method called “getAttribute()”:
animal = Animal.new()
animal.getAttribute(“WEIGHT”)
If there’s an annotation called “WEIGHT”, the weight is returned,
otherwise “nil”. The thing is: I don’t want to write “getAttribute
(XYZ)” each time to get the data. I want to write:
animal.weight
But there is no predefined accessor method called “weight”. Some how,
I must catch this. I’ve got two ideas, of which I’m not sure whether
they make sense and can be implemented:
-
The accessor methods are created dynamically at runtime, so that
they internally access the annotation data and return what they’ve
found or “nil”. -
A kind of “catch-all”-method which takes the name of the methode,
which we try to call, as a parameter. Some pseudo-code:
catchAll(nameOfDesiredMethod)
FindAnnotation(nameOfDesiredMethod) // returning attribute value or
nil
end
I don’t know, if there’s a known technique for this kind of problem.
But I know, that there’s something similar, if you look at the
ActiveRecord find() method. There you can say find_by_attribute, for
example.
It’s hard to explain, I did my best.
Thank you for your suggestions!
Best wishes,
ms