Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'Monkey Patching' exactly Mean in Ruby?

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 
like image 895
Yaser Sulaiman Avatar asked Dec 26 '08 19:12

Yaser Sulaiman


People also ask

How does monkey patch work?

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.

Why is it called monkey patching?

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.

What is monkey patching and is it ever a good idea?

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.

What is monkey patching in Javascript?

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.


1 Answers

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.

like image 91
RSK Avatar answered Sep 19 '22 20:09

RSK