Phrogz wrote:
> 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?

Just a constant lookup issue for a closure. Doing
this would also work:

  puts "Block: BAR is #{self.class.const_get 'BAR'}"

Though it may not be the cleanest solution :)


E

-- 
Posted via http://www.ruby-forum.com/.