Most inheritance questions I’ve seen assume that the child classes have different attributes than the super class. For example, Person may be the super class, and Driver a subclass, where Driver has everything Person has plus a license_type field.
I’m asking a slightly different question. I have a super class, call it Entity, and Entity has an object_type field, describing what type of Entity we have. All types have the same fields, but each type behaves slightly differently. For example, the add method is different for different Entity types.
My currently solution is to subclass Entity and whenever I fetch an Entity (e.g., in find() or where(..)), I call entity = entity.becomes(eval("Entity#{entity.object_type}")). This is ugly and doesn’t work that well, for example url_for and form_for will call undefined methods, because the class type is Entity<Type>, not Entity.
How would I go about having model inheritance without table inheritance, such that urls, paths, forms, and everything else still works as described? And maybe there’s a way for me to avoid calling .becomes(..), too? What I’m doing is very ugly ;).
I’ve learned more about Ruby and Rails and I’ve come up with a good solution. I changed my
Entity<Type>classes to modules and put them inlib/. Then, in the Entity class, I have anafter_initializecallback that looks like this:This way, all the methods defined in
EntityType1andEntityType2are executed in the scope of theEntityclass, without requiring any new class instantiation. So far the solution has been working well, though I’ve only been using it for a few days now.