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