Forum: Ruby const_missing - why is it necessary to hook it at Module?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
260b864377cc125e575de59843cb02b3?d=identicon&s=25 Clifford Heath (Guest)
on 2007-03-18 08:00
(Received via mailing list)
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.
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 David A. Black (Guest)
on 2007-03-18 13:15
(Received via mailing list)
Hi --

On 3/18/07, Clifford Heath <no.spam@please.net> wrote:
>         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
260b864377cc125e575de59843cb02b3?d=identicon&s=25 Clifford Heath (Guest)
on 2007-03-19 01:01
(Received via mailing list)
David A. Black wrote:
> 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.
260b864377cc125e575de59843cb02b3?d=identicon&s=25 Clifford Heath (Guest)
on 2007-03-20 04:21
(Received via mailing list)
Clifford Heath wrote:
> Would you be interested in private
> communication regarding this project?

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

Clifford Heath.
This topic is locked and can not be replied to.