开发者

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

开发者 https://www.devze.com 2023-03-06 03:19 出处:网络
I\'m experimenting with meta programming and want to dynamically create a class that inherits from ActiveRecord.

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开发者_JS百科 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.


Try to do this:

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

精彩评论

暂无评论...
验证码 换一张
取 消