According to Wikipedia, a monkey patch is:
a way to extend or modify the runtime code of dynamic languages [...] without altering the original source code.
The following statement from the same entry confused me:
In Ruby, the term monkey patch was misunderstood to mean any dynamic modification to a class and is often used as a synonym for dynamically modifying any class at runtime.
I would like to know the exact meaning of monkey patching in Ruby. Is it doing something like the following, or is it something else?
class String def foo "foo" end end
A monkey patch is a way to change, extend, or modify a library, plugin, or supporting system software locally. This means applying a monkey patch to a 3rd party library will not change the library itself but only the local copy of the library you have on your machine.
Etymology. The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily – and possibly incompatibly with other such patches – at runtime. The word guerrilla, nearly homophonous with gorilla, became monkey, possibly to make the patch sound less intimidating.
Monkey patching is good for testing or mocking out behavior. They can be localized in factory/class decorators/metaclasses where they create a patched new class/object from another object to help with "cross-cutting concerns" in between ALL methods like logging/memoization/caching/database/persistance/unit conversion.
Monkey patching is more a way for debugging, experiencing, patching, or hacking existing code than rather a long-term solution for a code base, even if it could be used as a natural solution in a few specific cases.
The best explanation I heard for Monkey patching/Duck-punching is by Patrick Ewing in RailsConf 2007
...if it walks like a duck and talks like a duck, it’s a duck, right? So if this duck is not giving you the noise that you want, you’ve got to just punch that duck until it returns what you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With