Creating a Runtime Class in Rails. How should I handle this?

I am working on a reporting and registration system that will act as a window for viewing statistics of other applications. I want ORM ActiveRecord functionality, but you do not have application database structures before you start.

Additional databases are defined in database.yml, and then I connect to the 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

  • Create classes (from tables) on the fly and
  • bind them to external database tables

Am I approaching this wrong? How can I better use namespacing for external databases, allowing the creation of dynamic classes.

Suggestions and help appreciated.

+3
source share
1 answer

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.

+1
source

Source: https://habr.com/ru/post/1784676/


All Articles