在Ruby的类层次结构中,如何列出包含在特定类中的模块?如下所示:
module SomeModule
end
class ParentModel < Object
include SomeModule
end
class ChildModel < ParentModel
end
p ChildModel.included_modules #=> [SomeModule]
p ChildModel.included_modules(false) #=> []
列出祖先会使模块在树中的位置更靠前:
p ChildModel.ancestors #=> [ChildModel, ParentModel, SomeModule, Object, Kernel]
发布于 2010-08-16 02:13:02
据我所知,这就是你要找的东西:
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
中?相反,为什么Kernel
没有被列为包含的模块,即使它在祖先链中与SomeModule
一样多?方法的布尔型参数是什么意思?
(请注意,布尔参数总是糟糕的设计:一个方法应该只做一件事。如果它接受一个布尔参数,根据定义它会做两件事,一是如果参数为真,另一件是参数为假。或者,如果它只做了一件事,那么这只能意味着它忽略了它的参数,在这种情况下,它不应该一开始就接受它。)
https://stackoverflow.com/questions/3488429
复制相似问题