Rubén Medellín
3/6/2008 1:35:00 AM
> 1) What's the correct way to doing this?
Don't know the "correct" way, there is always more than one form to do
it. This is what I would do
class Class
def generate(name)
klass = Class.new
klass.class_eval <<-EVAL
def to_s
"I'm a #{name}"
end
EVAL
const_set(name, klass)
end
end
class Universe
generate :Planet
puts Planet.new
puts Universe::Planet.new
end
puts Planet.rescue "No Planet!"
puts Universe::Planet.new
_______
I'm a Planet
I'm a Planet
No Planet!
I'm a Planet
_______
alternatively you could do
klass = Class.new do
def foo
#...
end
end
but then you can't pass a reference to the variable name. Don't know
if there's a way do do it, though.
If I wanted that to stick on a method, I would pass the binding as
well
class Factory
def self.generate(name, _binding)
eval <<-EVAL, _binding
class #{name}
def to_s
"Hello from #{name}"
end
end
EVAL
end
end
> 2) I would have thought the non-qualified class references would have
> generated exceptions.
Very intriguing. I would have expected the same