Module#const_missing redefinition

E

El Barto

I try to redefine #const_missing but it does not behave as I expect.

def Object.const_missing(sym)
puts "%s.const_missing: %s" % [self, sym]
end

class Test
def Test.const_missing(sym)
puts "%s.const_missing: %s" % [self, sym]
end

# OK: Test.const_missing
Bart
end

Test.new.instance_eval do
# Object.const_missing, why not Test.const_missing?
Bart
end

Test.module_eval do
# Object.const_missing, why not Test.const_missing?
Bart
end

Regards.
 
D

David A. Black

Hi --

I try to redefine #const_missing but it does not behave as I expect.

def Object.const_missing(sym)
puts "%s.const_missing: %s" % [self, sym]
end

class Test
def Test.const_missing(sym)
puts "%s.const_missing: %s" % [self, sym]
end

# OK: Test.const_missing
Bart
end

Test.new.instance_eval do
# Object.const_missing, why not Test.const_missing?
Bart
end

Test.module_eval do
# Object.const_missing, why not Test.const_missing?
Bart
end

I believe it's because of the pseudo-static way in which constants are
resolved. Spotted at parse-time, Bart is assumed to be a constant of
Object. If you change the first one to self.class::Bart, and the
second one to self::Bart, they will be resolved as Test::Bart.


David
 
S

Simon Kröger

It's getting better:

-----------------------------------------------------------
def Object.const_missing(sym)
puts "%s.const_missing: %s" % [self, sym]
end


class Test
Bart = 42

def Test.const_missing(sym)
puts "%s.const_missing: %s" % [self, sym]
end
end

Test.new.instance_eval do
# Object.const_missing, why not Test.const_missing?
Bart
end

Test.module_eval do
# Object.const_missing, why not Test.const_missing?
Bart
end

Test.module_eval "p Bart"
Test.new.instance_eval "p Bart"
-----------------------------------------------------------

output:

Object.const_missing: Bart
Object.const_missing: Bart
42
42

cheers

Simon
 

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,768
Messages
2,569,575
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top