MonkeyPatching in Ruby - simple example

MonkeyPatching in Ruby is actually extremely easy to understand and use.

We can monkey patch any ruby class, and this is how to do it.

 

WHEN WE SHOULD MONKEYPATCH?

  • if we want to fix the broken code inside some library
  • when we want to check something fast

 

HOW IT WORKS

For sure we all now reverse method belonging to the Array class.

["a", "b", "c"].reverse
=> ["c", "b", "a"]

It's quite common, and we use it on daily basis.

If we want to change the use of this method, we can just write in a new file:

# frozen_string_literal: true

class Array
  def reverse
    raise "Error Blocked"
  end
end

["a", "b", "c"].reverse

It will return an error instead of reversing the array.

 

BEST WAY TO DO IT

In modern programming people believe that just overriting a class is not a good idea. It can give us a lot of problems. 

For example we can monkey patch some method twice - it will be overrited, and we won't know what is happening.

It is good to monkey patch classes inside modules and then include them when we need it.

Check this out:

 

2177
All posts