cbmeeks
cbmeeks

Reputation: 11410

How can I dynamically create a class based off ActiveRecord at runtime? (Ruby)

I'm 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 to:

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 an Orders class

Any tips?

Thanks.

Upvotes: 3

Views: 1589

Answers (1)

bor1s
bor1s

Reputation: 4113

Try to do this:

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

Upvotes: 8

Related Questions