This post originated from an RSS feed registered with Ruby Buzz
by Ryan Davis.
Original Post: STI and Abstract Classes Driving You Nuts?
Feed Title: Polishing Ruby
Feed URL: http://blog.zenspider.com/index.rdf
Feed Description: Musings on Ruby and the Ruby Community...
class MyAbstractModel < ActiveRecard::Base
self.abstract_class = false
# ...
end
-----
class MySTIModel < MyAbstractModel
TYPES = %w(sub1 sub2 sub3)
def self.inherited(cls)
super
raise "not in #{self.class}::TYPES: #{cls}" unless TYPES.include? cls.name.downcase
end
end
MySTIModel::TYPES.each do |f|
require_dependency f
end
-----
class Sub1 < MySTIModel; end
class Sub2 < MySTIModel; end
class Sub3 < MySTIModel; end
It is a stupid bug and I can't do much about it, but the above workaround seems to be a nice tradeoff between horrible hack and maintainability. By pushing the list of subclasses up to the TYPES array, you keep it visible and near the top of the file. By having the inherited hook, you keep slipups in maintainability as visible as possible.