Ruby Language Monkey Patching in Ruby Safe Monkey patching with Refinements

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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"


Got any Ruby Language Question?