Dynamic Class Definition WITH a Class Name
The name of a class is simply the name of the first constant that refers to it.
I.e. if I do myclass = Class.new
and then MyClass = myclass
, the name of the class will become MyClass
. However I can't do MyClass =
if I don't know the name of the class until runtime.
So instead you can use Module#const_set
, which dynamically sets the value of a const. Example:
dynamic_name = "ClassName"
Object.const_set(dynamic_name, Class.new { def method1() 42 end })
ClassName.new.method1 #=> 42
I've been messing around with this too. In my case I was trying to test extensions to ActiveRecord::Base. I needed to be able to dynamically create a class, and because active record looks up a table based on a class name, that class couldn't be anonymous.
I'm not sure if this helps your case, but here's what I came up with:
test_model_class = Class.new(ActiveRecord::Base) do
def self.name
'TestModel'
end
attr_accessor :foo, :bar
end
As far as ActiveRecord is concerned, defining self.name was enough. I'm guessing this will actually work in all cases where a class cannot be anonymous.
(I've just read sepp2k's answer and I'm thinking his is better. I'll leave this here anyway.)