create a class in a class with eval

G

Gaspard Bucher

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
 
D

David A. Black

Hi --

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

You could do:

Module.module_eval "class A; end"

or (preferable, in my opinion):

Module.const_set("A", Class.new)


David

--
Upcoming training from Ruby Power and Light, LLC:
* Intro to Ruby on Rails, Edison, NJ, October 23-26
* Advancing with Rails, Edison, NJ, November 6-9
Both taught by David A. Black.
See http://www.rubypal.com for more info!
 
G

Gaspard Bucher

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top