Ruby:在模块的单例类中重新定义const_missing方法



Singleton class中重新定义const_missing方法似乎Module不起作用。但是如果我直接在类Module中重新定义它就可以了。有什么原因吗?

class Module
  class << self
    def const_missing(constant)
      puts "This doesn't work!"
    end
  end
end
Hello

以下工作在哪里!

class Module
  def const_missing(constant)
    puts 'This works!'
  end
end
Hello

背景

  • 尝试在常量属于不可覆盖的类别的情况下使用 super。假设与模式不匹配的常量仍会导致NameError

为什么你认为在模块的特征类上定义const_missing不起作用?它完美地工作:

▶ class Module
▷   class << self  
▷     def const_missing(constant)    
▷       puts "This doesn't work!"      
▷     end      
▷   end    
▷ end  
#⇒ :const_missing
▶ Module::F
#⇒ This doesn't work!

问题是你想实现什么?当您调用Module/Class调用它时,您是否有兴趣处理常量,例如:

module M ; end
puts M::MissingConst

你应该在M的特征类上实现const_missing。哪个单例的超类显然是Module类本身,而不是模块的特征类(M.singleton_class.superclass => Module)。

是否要处理不带命名空间的标题大小写名称引用几乎所有常量,都可以使用:

class Object
  class << self
    def const_missing(name)
      puts 'bingo '
    end
  end
end
▶ F
#⇒ bingo 

最新更新