Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Ruby Class on the fly without eval

I need to create a Ruby class on the fly, i.e. dynamically, that derives from ActiveRecord::Base. I use eval for the time being:

eval %Q{
  class ::#{klass} < ActiveRecord::Base
    self.table_name = "#{table_name}"
  end
}

Is there an equivalent, and at least equally concise way to do this without using eval?

like image 556
DrTom Avatar asked Jun 11 '12 12:06

DrTom


2 Answers

You can use the Class class, of which classes are instances. Confused yet? ;)

cls = Class.new(ActiveRecord::Base) do
  self.table_name = table_name
end

cls.new
like image 149
d11wtq Avatar answered Oct 24 '22 19:10

d11wtq


Of course, there is :)

class Foo
  class << self
    attr_accessor :table_name
  end
end

Bar = Class.new(Foo) do
  self.table_name = 'bars'
end

Bar.table_name # => "bars"
like image 4
Sergio Tulentsev Avatar answered Oct 24 '22 18:10

Sergio Tulentsev