代码之家  ›  专栏  ›  技术社区  ›  WPeN2Ic850EU

类的作用域猴子补丁

  •  1
  • WPeN2Ic850EU  · 技术社区  · 7 年前

    我需要修补一个类,但希望修补程序对某些模块是本地的。在Ruby中,我会:

    module ArrayExtension
      refine Array do
        def ===(other)
          self.include?(other)
        end
      end
    end
    
    module Foo
      using ArrayExtension
      def self.foo
        case 2
        when [1,2] then puts "bingo!"
        end
      end
    end
    
    Foo.foo          # => bingo!
    puts [1,2] === 2 # => false
    

    水晶里有类似的东西吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Samual    7 年前

    所以要重新定义 ===

    module Foo
      def ===(other)
        self.includes?(other)
      end
    end
    
    class CustomArray(T) < Array(T)
      include Foo
    end
    
    custom_array = CustomArray(Int32).new
    
    custom_array << 1
    custom_array << 2
    
    puts custom_array === 1 # true
    puts custom_array === 2 # true
    puts custom_array === 3 # false
    
    推荐文章