Create a class in a class with eval

I need to eval code that will create globally available classes. I tried
this :

class Test
def makeA
Module.send(:eval, “class A; end”)
# same with: eval “class A; end”
puts Test.const_get(‘A’) # => Test::A
puts Module.const_get(‘A’) # => raise NameError, why ?
end
end

eval “class B; end”
puts Module.const_get(‘B’) # => B

Test.new.makeA #=> bang

Thanks for your help.

Gaspard

Hi –

On Tue, 25 Sep 2007, Gaspard B. wrote:

eval “class B; end”
puts Module.const_get(‘B’) # => B

Test.new.makeA #=> bang

You could do:

Module.module_eval “class A; end”

or (preferable, in my opinion):

Module.const_set(“A”, Class.new)

David

Thanks for the answer. Works great.

I just changed Module to Object since:
Object.const_set(“A”, Class.new) ==> A
Module.const_set(“A”, Class.new) ==> Module::A

2007/9/25, David A. Black [email protected]:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs