Daniel DeLorme
2/6/2008 4:32:00 AM
Day wrote:
> Yes, but that doesn't answer the question, really, about why the scope
> is so counter-intuitive. (Though this is handy and cleaner-looking, so
> I'm going to seriously consider using it, as long as it matches up
> with how we want this to work). I just hate to fix a problem and not
> know why it worked.
I don't have a clear answer but I think it has something to do with the
fact that constants are lexically scoped.
Here is some code that should hopefully help:
class Foo
def self.add_class_1(name)
puts "from #{self}, create #{name} with class_eval"
class_eval %(
puts " nesting = %s" % Module.nesting.inspect
puts " self = %s" % self.inspect
#{name} = Class.new(self)
)
end
def self.add_class_2(name)
puts "from #{self}, create #{name} with eval"
eval %(
puts " nesting = %s" % Module.nesting.inspect
puts " self = %s" % self.inspect
#{name} = Class.new(self)
)
end
end
>> Foo.add_class_1("A").add_class_1("B")
from Foo, create A with class_eval
nesting = [Foo, Foo]
self = Foo
from Foo::A, create B with class_eval
nesting = [Foo::A, Foo]
self = Foo::A
=> Foo::A::B
>> Foo.add_class_2("C").add_class_2("D")
from Foo, create C with eval
nesting = [Foo]
self = Foo
from Foo::C, create D with eval
nesting = [Foo]
self = Foo::C
=> Foo::D