【问题标题】:Ruby: get a list of extended modules?Ruby:获取扩展模块列表?
【发布时间】:2011-03-04 17:31:24
【问题描述】:

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

@mymod.included_modules

获取包含的模块列表。

是否有列出扩展模块的模块的等价物?

module Feature1
end

module Feature2
  extend Feature1
end

Feature2.extended_modules #=> [Feature1]

【问题讨论】:

  • 祖先函数可能会有所帮助

标签: ruby


【解决方案1】:
Feature2.singleton_class.included_modules # => [Feature1, ...]

【讨论】:

  • 这应该是选择的答案。
【解决方案2】:

它们就在那里,你只需要在正确的地方寻找:

(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]

【讨论】:

  • 啊,是的。我现在记得这个。有一些德国名字与这是什么有关。
  • 我认为社区已经确定了单例类。 Ruby 1.9 中甚至还有一个Object#singleton_class 方法,它返回一个对象的单例类。这工作的原因当然是 extend 实际上只是 singleton_class.include
  • 我刚刚在 irb 中尝试了你的答案,它很棒:) 但它的 singleton_class.included_modules
【解决方案3】:

所有 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] }'

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多