Can you explain the problem you’re facing that’s lead you to determine
that dynamic classes are the solution?
It may be that people could suggest alternate solutions that might not
depend on the same functionality…
I currently have a table-less model that is a SearchModel, it has
attributes that correspond to MetaSearch parameters. The model also
has a to_where_hash option so convert itself into the appropaite hash
I chose this path because I can use the rails associations +
formtastic to generate the search forms on the fly based on the
SearchModel attributes. This part isn’t hard and works well.
So now, instead of writing specifically defining a class for each
model I want to create a search form for, I want to create a
GenericSearchObject that will build a specific search object using the
association reflections and public attributes.
Foo = Class.new(ActiveRecord::Base) do
def self.columns() @columns ||= ; end
def self.column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s,
default, sql_type.to_s, null)
has_many :bar_ids_in, :class_name => ‘Bar’
Foo.reflect_on_all_associations now indicates there is a
this creates a new foo class, and defines the association so
formtastic will play nice® with it.
Now here is why I want a dynamic constant…
When formtastic generates its fields it reflects on the classes as
well, by using “instance.class”. If i do not use the constant Foo, and
instead using the variable foo, the class returned will be Class,
instead of Foo. By dynamically generating these (unique) constant
names, the instances will properly reflect on itself.
I may be making my life overly complicated, but all of my irb tests
show this method working. When I’m done with this training I will try
to implement it unless anyone has any suggestions.