0

我有一个基本模块,它上面定义了所需的类,如下所示:

module Base
  class Desirable
  end
end

现在在一个嵌套的模块链(in Base::Nested1)中,我想从这个类派生。我首先尝试这样做:

module Base::Nested1
  class Derived < Desirable
  end
end

这会引发错误:

uninitialized constant Base::Nested1::Desirable

但是,如果我这样声明:

module Base
  module Nested1
    class Derived < Desirable
    end
  end
end

我没有错误。

错误是由这部分const_missing方法引起的(在 rails activesupport 5.0.1 中):

517       elsif (parent = from_mod.parent) && parent != from_mod &&
518             ! from_mod.parents.any? { |p| p.const_defined?(const_name, false) }
519         # If our parents do not have a constant named +const_name+ then we are free
520         # to attempt to load upwards. If they do have such a constant, then this
521         # const_missing must be due to from_mod::const_name, which should not
522         # return constants from from_mod's parents.

我的问题是我不明白该代码的注释;在这种情况下,为什么我们不应该从父模块加载这个常量?

4

0 回答 0