Scoped monkey-patching of a class

208 Views Asked by At

I need to patch a class, but want the patch be local to some module(s). In Ruby I would do:

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

Is there something similar in Crystal?

1

There are 1 best solutions below

0
On BEST ANSWER

So to redefine === you just define it again.

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