如何使模块包含在类中

如何使模块包含在类中

本文介绍了如何使模块包含在类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



请注意, ancestors

code>,< => included_modules 将无法工作,因为他们的结果不区分模块都包含在超类前面的模块中。换句话说,他们无法区分以下两种情况:




  • M 被添加到 B

      end 
    class B<一个; 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

      end 
    class B<一个; end
    module M; end
    B.include M

    B.ancestors#=> [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


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:

  • M is prepended to the superclass of 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 is included in 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]
    

解决方案
mixed_in  = B.included_modules[0...-B.superclass.included_modules.size]
prepended = B.ancestors.take_while { |ancestor| ancestor != B }
included  = mixed_in - prepended

这篇关于如何使模块包含在类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:08