How can I dynamically create an ActiveRecord-based class at runtime? (Ruby)

I am experimenting with meta-programming and want to dynamically create a class that inherits from ActiveRecord.

For example, I can do this:

Object.const_set("Orders", Class.new { def blah() 42 end })

So now I can:

o = Orders.new
o.blah   #<== 42

But when I try:

Object.const_set("Orders", Class.new < ActiveRecord::Base { def blah() 42 end })

Gives me a syntax error and

Object.const_set("Orders", Class.new { def blah() 42 end } < ActiveRecord::Base)

Doesn’t complain until I try to instantiate the class Orders

Any tips?

Thank.

+3
source share
1 answer

Try to do this:

SomeClass = Class.new(ActiveRecord::Base) do
  .... #some behaviour
end
+6
source

All Articles