Instance_eval and constants


(Aron Griffis) #1

Hello,

I think this used to work in the past, but isn’t working with recent
Ruby versions (since sometime in the 1.6.x stream):

class MyClass
SomeConstant = 1
def MyClass.block(&block)
instance_eval(&block)
end
end

MyClass.block { puts SomeConstant }

Now it says:

NameError: uninitialized constant SomeConstant

In order to make it work, I have to define:

class MyClass
def MyClass.method_missing(name)
constant = name.to_s
constant = constant[0…0].upcase + constant[1…-1]
eval constant
end
end

Then I can effectively use lower-case accessor functions for the
constants:

MyClass.block { puts someConstant }

Is it possible to make it work without this crutch?

Thanks,
Aron


(Joel VanderWerf) #2

Aron Griffis wrote:

Hello,

I think this used to work in the past, but isn’t working with recent
Ruby versions (since sometime in the 1.6.x stream):

class MyClass
SomeConstant = 1
def MyClass.block(&block)
instance_eval(&block)
end
end

MyClass.block { puts SomeConstant }

 MyClass.block { puts self::SomeConstant }

That overrides the static scoping, at least in the current 1.9.0. But I
don’t know what’s going to happen in the future.


(Aron Griffis) #3

Joel VanderWerf wrote: [Tue Feb 24 2004, 05:50:04PM EST]

MyClass.block { puts self::SomeConstant }

Sure, but that obviates the point of the code, doesn’t it? In that case
I could have just used MyClass::SomeConstant. The point of
MyClass.block was to expose the constant names for ease of use.

The thing I don’t understand is… why are method names exposed to the
namespace with instance_eval but constant names are not?

Aron