Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create a class inherited from ActiveRecord?

I want to be able to dynamically create classes, for scripting outside my Rails app, that inherit from ActiveRecord.

I'm stuck on something like this:

require 'active_record'

def create_arec(table_name)
  Class.new ActiveRecord::Base do
    self.table_name = table_name
    yield
  end
end

Band = create_arec 'bands' do
  scope :only_rock, -> {where genre: 'rock'}
end

rock_bands = Band.only_rock #undefined method `only_rock'

How do I make it work, or can someone show me better way to do it?

like image 499
Ondřej Želazko Avatar asked Oct 11 '13 13:10

Ondřej Želazko


1 Answers

Nailed it:

def create_arec(table_name, &block)
  klass = Class.new(ActiveRecord::Base){self.table_name = table_name}
  klass.class_eval &block
  klass
end

thanks @phoet

like image 191
Ondřej Želazko Avatar answered Nov 17 '22 18:11

Ondřej Želazko