问题
How can I get an array of modules included in a class, excluding those that slipped in through inheritance?
Notice that ancestors, <=>, included_modules will not work because their results do not distinguish modules that are included from modules that are prepended in a superclass. In other words, they cannot distinguish the following two cases:
Mis prepended to the superclass ofBclass 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]Mis included inBclass 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]
回答1:
mixed_in = B.included_modules[0...-B.superclass.included_modules.size]
prepended = B.ancestors.take_while { |ancestor| ancestor != B }
included = mixed_in - prepended
来源:https://stackoverflow.com/questions/34484006/how-to-get-the-modules-included-in-a-class