如何获取类中包含的模块数组,不包括那些通过继承传入的模块?
请注意ancestors
,<=>
,included_modules
不起作用,因为它们的结果不区分包含在超类中预先添加的模块中的模块。换句话说,他们无法区分以下两种情况:
M
前置于B
class A; end
class B < A; end
module M; end
A.prepend M
B.ancestors # => [B, M, A, Object, Kernel, BasicObject]
B <=> M # => -1
B.included_modules # => [M, Kernel]
M
包含在B
class A; end
class B < A; end
module M; end
B.include M
B.ancestors # => [B, M, A, Object, Kernel, BasicObject]
B <=> M # => -1
B.included_modules # => [M, Kernel]
答案 0 :(得分:2)
mixed_in = B.included_modules[0...-B.superclass.included_modules.size]
prepended = B.ancestors.take_while { |ancestor| ancestor != B }
included = mixed_in - prepended