What does 'Monkey Patching' exactly Mean in Ruby?

后端 未结 8 1969
半阙折子戏
半阙折子戏 2020-11-27 03:29

According to Wikipedia, a monkey patch is:

a way to extend or modify the runtime code of dynamic languages [...] without altering the original sou

相关标签:
8条回答
  • 2020-11-27 03:51

    You are correct; it's when you modify or extend an existing class rather than subclass it.

    0 讨论(0)
  • 2020-11-27 03:55

    Explanation of the concept without code:

    It means you can dynamically modify code. Wanna add a method dynamically to a particular class known only at runtime? No problem. It's powerful, yes: but can be misused. The concept might be a little too esoteric to understand, so I have prepared an example below which does not use ANY code:

    How to monkey patch a car:

    Normal Car Operations

    How do you normally start a car? It’s simple: you turn the ignition, the car starts!

    Great, but how can we "monkey patch" the car class?

    This is what Fabrizzio did to poor Mikey. Normally, if you want to change how a car operates, you would have to make those changes in the car manufacturing plant (i.e. within the Car class). Fabrizzio ain't got no time for that: he monkey patches cars by getting under the bonnet to surreptitiously and sneakily rewire things. In other words, he re-opens the Car class, makes the changes he wants, and he's done: he's just monkey patched a car.

    You have to really know what you are doing when you monkey patch otherwise the results could be quite explosive.

    Fabrizzio, where are you going?

    Boom!

    Like Confucius Say:

    "Keep your source code close, but your monkey patches closer."

    It can be dangerous.

    0 讨论(0)
提交回复
热议问题