3

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

  1. Create classes (from tables) on the fly and
  2. 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.

Pär Wieslander
  • 28,374
  • 7
  • 55
  • 54
EarlyPoster
  • 1,068
  • 1
  • 11
  • 27

1 Answers1

1

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.

Toby Hede
  • 36,755
  • 28
  • 133
  • 162