如何列出Ruby类中包含的模块?

如何列出Ruby类中包含的模块?,ruby,metaprogramming,module,Ruby,Metaprogramming,Module,在Ruby的类层次结构中,如何列出包含在特定类中的模块?大概是这样的: module SomeModule end class ParentModel < Object include SomeModule end class ChildModel < ParentModel end p ChildModel.included_modules #=> [SomeModule] p ChildModel.included_modules(false) #=> []

在Ruby的类层次结构中,如何列出包含在特定类中的模块?大概是这样的:

module SomeModule
end

class ParentModel < Object
  include SomeModule
end

class ChildModel < ParentModel
end

p ChildModel.included_modules #=> [SomeModule]
p ChildModel.included_modules(false) #=> []

据我所知,你的问题是这样的:

class Class
  def mixin_ancestors(include_ancestors=true)
    ancestors.take_while {|a| include_ancestors || a != superclass }.
    select {|ancestor| ancestor.instance_of?(Module) }
  end
end
然而,我不完全理解您的测试用例:为什么
SomeModule
被列为
ChildModel
的包含模块,即使它实际上没有包含在
ChildModel
中,而是包含在
ParentModel
中?相反,为什么
内核
没有被列为包含的模块,即使它与
某些模块
一样位于祖先链中?这个方法的布尔参数意味着什么


(注意,布尔参数总是糟糕的设计:一个方法应该只做一件事。如果它接受一个布尔参数,根据定义它会做两件事,一件是如果参数为真,另一件是参数为假。或者,如果它只做一件事,那么这只能意味着它忽略了它的参数,在这种情况下,它不应该以它开始w。)ith.)

我不是最初的海报,但我想我可以回答你的问题:布尔参数。兰斯期待这个
。包含的模块
方法的行为类似于
#方法
#公共#方法
和Ruby中的其他类似方法。在这些方法上,
true
值表示“显示此对象从其类获得的方法以及从其祖先类和包含的模块获得的方法”。假值不会返回这些附加方法。
class Class
  def mixin_ancestors(include_ancestors=true)
    ancestors.take_while {|a| include_ancestors || a != superclass }.
    select {|ancestor| ancestor.instance_of?(Module) }
  end
end