Gavin Kistner
2/26/2006 5:19:00 PM
I'm writing a DSL, and I want to use some constants. To be clean, I
don't want to pollute the global constant space. To be tight, I also
don't want the user to have to scope the constant using Foo::BAR, but
instead be able to use just BAR.
The following surprised me. As the scope of the block is an instance of
Foo, I had hoped/assumed that it would have access too Foo's constants.
Alas, no.
class Foo
BAR = 1
def initialize( &block )
instance_eval &block
end
def bork
puts "bork: self is #{self}"
puts "bork: BAR is #{BAR}!"
end
end
Foo.new{
bork
puts "block: self is #{self}"
puts "block: BAR is #{BAR}!"
}
#=> bork: self is #<Foo:0x32c808>
#=> bork: BAR is 1!
#=> block: self is #<Foo:0x32c808>
#=> NameError: uninitialized constant BAR
For now, I'll just shove my constants into global space before the
instance_eval, and remove them afterwards. Is there a better/cleaner
way to accomplish my goals?