繁体   English   中英

如何在模块定义之外访问 Module.nesting 的返回

[英]How to access the return of Module.nesting outside of the module definition

使用 Module.nesting 方法时,我可以从调用点返回嵌套模块列表。 我在文档和其他地方看到的唯一示例显示了从嵌套模块定义中放置和运行的方法调用:

module M1
  module M2
    Module.nesting #=> [M1::M2, M1]
  end
end

在以下示例中:

module A
  module B; end
  module C
    module D
      # I want to access the name-space chain from this point
    end
  end
end

# But how can I reference it from our here?
# A::C::D .... ?

一旦定义了模块,有没有办法检查模块中的名称空间链?

我能看到的唯一例子是在定义中创建一个变量来保存生成的调用,以便在定义之外再次引用:

module A
  module B; end
  module C
    module D
      $chain = Module.nesting
    end
  end
end

p $chain 
#=> [A::C::D, A::C, A]

有没有一种方法可以向上查找这个名称间距链,而无需在定义中创建一个变量供以后引用?

在 Ruby 中,“记住”表达式值的方法是将该值赋给变量。

此外,模块定义的值是在主体内计算的最后一个表达式的值。

如果你把两者放在一起,你会得到这样的东西:

chain = module A
  module B; end
  module C
    module D
      Module.nesting
    end
  end
end

p chain 
# [A::C::D, A::C, A]

考虑问题中提到的以下嵌套模块。

module A
  module B; end
  module C
    module D
      Module.nesting
    end
  end
end
  #=> [A::C::D, A::C, A] 

现在试试这个:

module A::C::D
  Module.nesting
end
  #=> [A::C::D]

Module::nesting字典顺序解析模块的嵌套,这意味着模块按它们的包含点排序,从A::C::D开始并向外工作。 Module::nesting不会“记住”定义模块的嵌套; 它只是在本地检查代码。 这与子类化相反。

也许您可以使用ObjectSpace::each_method方法获取所需的信息。

outer_module = A
ObjectSpace.each_object(Module).select { |m| m.to_s.match?(/\A#{outer_module}::/) }
  #=> [A::B, A::C::D, A::C]

暂无
暂无

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

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