const_missing - why is it necessary to hook it at Module?

C

Clifford Heath

Why doesn't the following code work?

class Foo
def Foo.const_missing(sym)
p sym
sym.to_s
end
end

Foo.new.instance_eval {
Bar
}

I thought the missing constant Bar would be caught
by the const_missing, since it's available on the
class whose instance is being instance_eval'd.

What gives? I'm writing a DSL and want to catch missing
constants within a block being instance_eval'd

Clifford Heath.
 
D

David A. Black

Hi --

Why doesn't the following code work?

class Foo
def Foo.const_missing(sym)
p sym
sym.to_s
end
end

Foo.new.instance_eval {
Bar
}

I thought the missing constant Bar would be caught
by the const_missing, since it's available on the
class whose instance is being instance_eval'd.

What gives? I'm writing a DSL and want to catch missing
constants within a block being instance_eval'd

All that instance_eval does is set self and execute the block.
Constants don't depend on self for their scope; they use a kind of
quasi-static scoping, and the Bar in your block is resolved
(unsuccessfully) as Bar from the top level.

You'd need to add your const_missing method to Object, so as to cover
the top level.


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
 
C

Clifford Heath

David said:
Constants don't depend on self for their scope; they use a kind of
quasi-static scoping

Ok, thanks David, I figured it was something like that.
There are very few cases where const_missing gets used
(Rails and Rake being two), and it's not obvious from
them or from the documentation that it works like that.

BTW, I recently saw a video of your "Curious developer"
talk on database design at the RailsConf 2006. I expect
to address many of the issues through my "ActiveFacts"
project (this DSL I'm working on is a fact-based data
modeling language). Would you be interested in private
communication regarding this project?

Clifford Heath.
 
C

Clifford Heath

Clifford said:
Would you be interested in private
communication regarding this project?

David, I got your response. Perhaps you didn't see mine?

Clifford Heath.
 

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