I have a rather unique class that allows its child classes to declare virtual fields. The child can declare virtual fields stored as XML by calling a method of the parent class like this:
class Child1 < Parent
create_xml_field ["readings", "usage"]
end
I have managed to get it working via a nasty work around. The create_xml_field method stores the field names in Class variable (see below). The init_xml_fields method is called from inside the after_initialize method.
class Parent < ActiveRecord::Base
def self.create_xml_field(fields)
@@xml_fields[self.name] = fields
end
def init_xml_fields(xml_fields)
xml_fields.each do |f|
f=f.to_sym
self.class_eval do
define_method(f) { ... } # define getter
define_method(f) { ... } # define setter
attr_accessible(f) # add to mass assign OK list, does not seem to work!
end
end
end
protected
def after_initialize
init_xml_fields
end
end
Nasty enough eh? I'm not proud, but I am having trouble making it work. Also, the work around doesn't work with mass-assignment of form parameters.
Does anyone have experience calling attr_acessible dynamically to allow mass-assignment in the child class? Thank you in advance!
This post was edited for clarity!