Safe monkey patching with refinements

suggest change

Since Ruby 2.0, refinements can limit a monkey patch to the scope that activates it with using.

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 # => "olleh"
AClassWithMP.new("hello").reverse # => "Hell riders"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents