Constant lookup as-if toplevel

I

Intransition

I'm evaluating a ruby script against a testing DSL that I wrote. Now I
would have loved to run the scripts at the toplevel, but the
contamination of the Object class makes that infeasible. So I run them
within a Scope object. Basically:

class Scope < Module

def initialize
extend self
end

def execute(script, filename)
eval(script, binding, filename)
end

end

My problem arises when a script uses a constant that isn't defined and
the error message looks like this:

ERROR: NameError uninitialized constant #<Scope:0x7f3cc21e5630>::Foo

I'm trying to find a way to get rid of the `#<Scope:...>::` part. To
the end user it should at least *look* like things are running at
toplevel.

I tried adding to Scope:

def inspect; ""; end

But that did not work. Any ideas?
 
T

Tony Arcieri

[Note: parts of this message were removed to make it a legal post.]

I ran into this same problem today myself, although attempting something
different. I wanted to stylize a constant name with a bang! Our company's
name happens to be stylized with a bang, so I thought I'd be silly and try
to translate that into Ruby itself (I was inspired by Rainbows!)

So I tried this:

http://gist.github.com/653850

<http://gist.github.com/653850>Which is fine, but when I created classes
within the namespace of my bangmodule, they still inspect without the bang!

I want the bang! Bring on the bang!
 
J

John Mair

Why not add a const_missing() to your Scope class and explicitly lookup
the constant on Object there, which will fail, and so the error will be
as if a top-level constant wasn't found.
 
J

John Mair

err, that should be:

class Scope
def self.const_missing(const)
Object.const_get(const)
end
end

John
 
R

Robert Dober

yup

def execute( script, filename )
eval(script, Module.new.send:)binding), filename)
end
execute( "Foo", "here" )

which gives

here:1:in `execute': uninitialized constant Object::Foo (NameError)

does this suit your needs better?
If this still causes the conflicts you were talking about, I like John's idea.

HTH
R
 
I

Intransition

err, that should be:

=A0 =A0 class Scope
=A0 =A0 =A0 def self.const_missing(const)
=A0 =A0 =A0 =A0 Object.const_get(const)
=A0 =A0 =A0 end
=A0 =A0 end

Nice. I removed `self.` b/c Scope is a self extended module, and it
looks good.

Thanks.
 

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,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top