Monkey patch

Tram Ho

1. What is Monkey patch

  • Is a feature of ruby ​​that allows you to edit an existing function or add a new function to any class.

a. Add a new method to the class

  • The following code will raise the error NoMethodError (undefined method shuffle for "aaa":String)
  • The reason is that the String class has no shuffle method
  • We can use monkey path to add the shuffle method to the String class

b. Modify the method available in the class

  • Similarly we can also use monkey path to edit methods available in class
  • For example

2. How to organize code with monkey patch

  • Monkey patch is a powerful tool that can also cause errors and debugging if not used and well organized.
  • In the above examples I have monkey path directly into the class
  • It is not a good way for the following reasons.

i. The code will be overridden

  • When a method has 2 monkey-paths, the second path will overide the 1st path and affect the code that runs on the 1st path.
  • For example:

ii. Can’t handle whether I’m using monkey path or not

  • When you don’t want to use monky-path, you only have to re-comment the monkey path code
  • However, doing so will affect the code that is running correctly with monkey path

iii. Solution

  • Use the module containing monkey path and include only when needing to use monkey path

Share the news now

Source : Viblo