如何将模块包含在类中

时间:2015-12-27 19:27:33

标签: ruby class inheritance module subclass

如何获取类中包含的模块数组,不包括那些通过继承传入的模块?

请注意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]
    

1 个答案:

答案 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