简体   繁体   English

当引用失败Object.const_defined?的常量时,它不会调用const_missing

[英]When referencing a constant that fails Object.const_defined?, it doesn't invoke const_missing

I am hitting a problem that a constant is being mapped to a wrong file. 我遇到一个将常量映射到错误文件的问题。 When debugging it, it shows weird things: 调试时,它显示出奇怪的东西:

=> 1: class App::CloudCredential < App::Credential
   2: end
(byebug) Object.const_defined? "App::Credential"
false
(byebug) App::Credential
App::Shared::Credential
(byebug) App::Credential.class
Module
(byebug) App::Credential.name
"App::Shared::Credential" 

My questions are that when Object.const_defined? "App::Credential" 我的问题是,何时Object.const_defined? "App::Credential" Object.const_defined? "App::Credential" returns false , Object.const_defined? "App::Credential"返回false

  1. why this wouldn't lead to const_missing ? 为什么这不会导致const_missing
  2. why referencing it still print something (which is wrong) as if the constant is defined (against what Object.const_defined? tells me) 为什么引用它仍会打印出一些东西(这是错误的),就像定义了常量一样(反对Object.const_defined?告诉我)
  3. Basically I'd like to know under what situation (or what kind of test I can use in byebug ) that would lead to const_missing . 基本上,我想知道什么情况下(或可以在byebug使用哪种测试)导致const_missing I am trying to find out why this App::Credential is being mapped to a complete wrong file (that of App::Shared::Credential ) 我试图找出为什么将此App::Credential映射到一个完整的错误文件( App::Shared::Credential

More information: This App::Shared::Credential is actually a module that is being included from the class App::Credential and this App::Shared::Credential has been included by another class. 详细信息:此App::Shared::Credential实际上是包含在class App::Credential的模块,而该App::Shared::Credential已被另一个类包含。

Thanks 谢谢

What you describe is not inconsistent at all. 您所描述的完全不是矛盾的。

When you try to access App::Credential , you are looking it up in the current constant namespace, but when you are using const_defined? 当您尝试访问App::Credential ,您正在当前常量名称空间中查找它,但是当您使用const_defined? , you are explicitly asking Object whether the constant is defined there . ,您明确询问Object是否在那里定义了常量。 But App::Credential could be defined in a subclass of Object , not in Object directly, and then this would return false . 但是App::Credential可以在Object的子类中定义,而不是直接在Object定义,然后这将返回false

module Foo
  module Bar
    Baz = 42
  end

  const_defined? 'Bar::Baz'
  #=> true

  Object.const_defined? 'Bar::Baz'
  #=> false
end

Since you are looking in two different places, it is perfectly sensible to get two different answers. 由于您在两个不同的地方查看,因此获得两个不同的答案是非常明智的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM