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
?
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With