Ruby:获取扩展模块列表?

22

当您在类或其他模块中包含模块时,您可以调用

@mymod.included_modules

获取包含的模块列表。

是否有相应的方法列出扩展了某个模块的模块列表?

module Feature1
end

module Feature2
  extend Feature1
end

Feature2.extended_modules #=> [Feature1]

祖先函数可能会有所帮助。 - Brandon Frohbieter
3个回答

37
Feature2.singleton_class.included_modules # => [Feature1, ...]

3
这应该是被选中的答案。 - Aeramor

19

那些东西确实存在,你只需要在正确的地方查找:

(class << Feature2; self end).included_modules   # [Feature1, Kernel]

我们可以这样概括:

class Module
  # Return any modules we +extend+
  def extended_modules
    (class << self; self end).included_modules
  end
end

# Now get those extended modules peculiar to Feature2
Feature2.extended_modules - Module.extended_modules # [Feature1]

1
啊,没错。我现在记起来了。这个东西有一个与德国相关的名称。 - Mario
11
我认为社群已经采用了“单例类”这个术语。在Ruby 1.9中,甚至有一个Object#singleton_class方法来返回对象的单例类。这个方法之所以能够运作,当然是因为extend本质上就是singleton_class.include - Jörg W Mittag
我刚在irb中尝试了你的答案,真是太棒了 :)但它的singleton_class.included_modules - zotherstupidguy

1
所有的 Ruby 模块都可以从 CLI(命令行)本身列出,如下所示:
ruby -e 'puts Gem::Specification.all().map{|g| [g.name, g.version.to_s] }'

或者

ruby -rubygems -e 'puts Gem::Specification.all().map{|g| [g.name, g.version.to_s] }'

希望这在一定程度上有所帮助!!!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接