您如何列出Ruby类中包含的模块? [英] How do you list included Modules in a Ruby Class?

查看:99
本文介绍了您如何列出Ruby类中包含的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would you list out the modules that have been included in a specific class in a class hierarchy in Ruby? Something like this:

module SomeModule
end

class ParentModel < Object
  include SomeModule
end

class ChildModel < ParentModel
end

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

列出祖先使模块在树中显得更高:

Listing the ancestors makes the module appear higher in the tree:

p ChildModel.ancestors #=> [ChildModel, ParentModel, SomeModule, Object, Kernel]

推荐答案

据我所知,您正在寻找这样的东西:

As far as I understand your question, something like this is what you are looking for:

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的包含模块,即使中实际上没有包含 却将SomeModule列为ChildModel c3>?相反,为什么Kernel 没有列为包含的模块,即使它在祖先链中与SomeModule一样多?该方法的布尔参数是什么意思?

However, I don't fully understand your testcases: why is SomeModule listed as an included module of ChildModel even though it isn't actually included in ChildModel but in ParentModel? And conversely, why is Kernel not listed as an included module, even though it is just as much in the ancestors chain as SomeModule? And what does the boolean argument to the method mean?

(请注意,布尔参数总是 不好的设计:一种方法应该恰好做一件事.如果它采用布尔参数,则它在定义上会做件事情,一件如果参数为true,则另一个参数为false;或者,如果仅做一件事,则只能表示它忽略了其参数,在这种情况下,不应以它开头.)

(Note that boolean arguments are always bad design: a method should do exactly one thing. If it takes a boolean argument, it does by definition two things, one if the argument is true, another is the argument is false. Or, if it does only one thing, then this can only mean that it ignores its argument, in which case it shouldn't take it to begin with.)

这篇关于您如何列出Ruby类中包含的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆