How to get the modules included in a class

我怕爱的太早我们不能终老 提交于 2019-12-10 15:17:19

问题


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]
    

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!