Ruby Language Safe Monkey patching with Refinements


Example

Since Ruby 2.0, Ruby allows to have safer Monkey Patching with refinements. Basically it allows to limit the Monkey Patched code to only apply when it is requested.

First we create a refinement in a module:

module RefiningString
  refine String do
    def reverse
      "Hell riders"
    end
  end
end

Then we can decide where to use it:

class AClassWithoutMP   
  def initialize(str)
    @str = str
  end
   
  def reverse
    @str.reverse
  end
end

class AClassWithMP
  using RefiningString

  def initialize(str)
    @str = str
  end
   
  def reverse
    str.reverse
  end
end

AClassWithoutMP.new("hello".reverse # => "olle"
AClassWithMP.new("hello").reverse # "Hell riders"