一类的范围猴子修补

时间:2018-11-15 16:03:11

标签: scope crystal-lang refinements

我需要修补一个类,但希望该修补对于某些模块是本地的。在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 个答案:

答案 0 :(得分:3)

因此,要重新定义===,只需重新定义即可。

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