instance_eval and constants

A

Aron Griffis

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
 
J

Joel VanderWerf

Aron said:
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.
 
A

Aron Griffis

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top