Monkey patching in Ruby
It is a way to override methods of a class at runtime. You can add new methods or modify existing ones.
In the following example we are monkey patching the to_s
method of the class String
:
class String
def to_s
puts 'I have been monkey patched'
end
end
'hey'.to_s
As you can see, this gives us a lot of possibilities, but we have to be very careful because this approach can lead to potential bugs that are very difficult to debug. Fortunately, Ruby already has a feature to add scope to our monkey patch. In the following example we will do the same but within a context:
module MyMonkeyPatch
refine String do
def to_s
puts 'I have been monkey patched'
end
end
end
# Now we can add our monkey patch to the global scope or inside any class:
class TestMyMonkeyPatch
using MyMonkeyPatch
def test
'test'.to_s
end
end
A good example of Monkey Patching in Rails is ActiveSupport, where we have vitaminized objects like 2.hours