Gavin McKenzie
2006-Jan-02 20:25 UTC
[Rails] Best practice for registering/discovering STI subclasses?
Folks, I''m fairly new to Rails, and I''ve Googled around for an answer to this question with no luck... Consider a little blog application that has uses single-table inheritance for the handful of different content types via a Content base class and subclasses like FooContent and BarContent. That part all works well for me. Now consider the view that presents actions to the user to create different types of content, via links like "Create new Foo" and "Create new Bar". I want the application to automatically be aware of the different types of content that are available so that, for instance, this list of links in the view is dynamically generated. I don''t want the app to have hard-coded in its initialization the knowledge that there are two types of Content classes, FooContent and BarContent. Brielfy the Class.inherited method looked promising as a way to detect subclassing, but doesn''t work for a couple of reasons including the fact that Rails doesn''t appear to load the FooContent or BarContent classes until ActiveRecord encounters a record of that type, which produces a chicken-and-egg problem when the table doesn''t contain any instances of a specific content class yet. Other methods of putting code in the class definition for the subclasses in order for them to register themselves as available content types with the application will fail for the same reason. So, any ideas? I''d like to be able to drop in a new type of content without having to change the main application in order to use it. Gavin