Runtime class creation in Rails. How should I handle this?
I'm working on a reporting and logging system that'll act as a viewport on the statistics of other applications. I want the ORM functionality of ActiveRecord, but do not have the DB structures of apps before hand.
The extra databases are defined in database.yml and I then connect with a class.
class externalapp < ActiveRecord::Base
establish_connection :externalapp_db
end
def create_class(class_name, superclass, &block)
klass = Class.new superclass, &block
Object.const_set class_name, klass
end
I need to be able to
- Create classes (from tables) on the fly and
- have them map to external database's tables
Am I approaching this incorrectly? How can I go about better namespacing the external databases, whilst 开发者_开发技巧allowing for dynamic class creation.
Suggestions and help appreciated.
I have experimented with this in the past:
constant_name = app.database_name.camelize + table_name.camelize
klass = Class.new(ActiveRecord::Base)
ActiveRecord::Base.const_set(constant_name, klass)
klass.class_eval do
set_table_name table_name
establish_connection(
:adapter => "mysql",
:host => app.database_host,
:username => app.database_username,
:password => app.database_password,
:database => app.database_name
)
end
So a pretty similar approach to yours.
精彩评论