I have several tables for enumerations. They all have the same content:
id, name, position. I''d like to avoid the tedious work of defining a
class for each one explicitly. Not least, in order to avoid clutter in
the model directory.
Here''s what I''ve come up with:
class EnumRecord < ActiveRecord::Base
def self.define_enums(*enums)
enums.each do |spec|
if spec.kind_of?(Hash)
class_name = spec[:class_name].to_s
raise ArgumentError, ''An enum specification must contain
a :class_name'' if class_name.empty?
order = spec[:order] || ''position''
table_name = spec[:table_name] || class_name
else
class_name = spec
end
module_eval("class #{class_name} < BoilerPlate::EnumRecord;
end")
enum_class = const_get(class_name)
enum_class.table_name = table_name
enum_class.preload(:order => order) # mixed-in somewhere else
end
end
end
Used like this in, say, environment.rb
EnumRecord::define_enums(
''Status'',
{:class_name => ''Criterion'', :table_name =>
''criteria'' }
)
Is there a more elegant way to achieve the same? How can I make sure the
enumeration classes are read-only?
Michael
--
Michael Schuerig Nothing is as brilliantly adaptive
mailto:michael-q5aiKMLteq4b1SvskN2V4Q@public.gmane.org as selective
stupidity.
http://www.schuerig.de/michael/ --A.O. Rorty, The Deceptive Self