Ruby uses the Monkey Patch Monkey Method for program development example, rubymonkey
Monkey Patch is a special programming technique. Monkey patch can be used to dynamically modify (expand) classes or modules at runtime. You can add a Monkey Patch to modify a third-party library that does not meet your needs, or you can add a Monkey Patch to modify errors in the code at zero time.
Source
Monkey patch was first called Guerrilla patch, which described it as a Guerrilla. Later, it was called Gorilla patch because of its similar pronunciation. Because the gorilla is not cute enough, it is later called Monkey patch.
Use Cases
In my understanding, Monkey patch has two application scenarios:
Urgent security patch, that is, Hotfix;
Modify or extend the attributes and methods in the library.
Example:
Alias:
class Monkey2 < Monkey def method2 puts "This is method2" end alias output method2 end monkey = Monkey2.new monkey.method2 monkey.output
Include:
Module Helper def help puts "Help... "end def method1 puts" helper method1... "end class Monkey include Helper def method1 puts" monkey method1... "end monkey = Monkey. new monkey. help monkey. method1 # The method of the current class takes precedence due to duplicate names
Undef:
class Monkey def method1 puts "This is method1" end end class Monkey2 < Monkey def method2 puts "This is method2" end end monkey = Monkey2.new monkey.method1 monkey.method2 class Monkey2 undef method1 undef method2 end monkey.method1 monkey.method2
We can also use undef_method or remove_method to implement the same function of undef <method_name>, for example:
class Monkey2 remove_method :method1 undef_method :method2 nd
When using the monkey Patch, you should also pay attention to the following:
1. basically only append the Function
2. Be cautious when performing function changes and try to make small changes.
3. Pay attention to mutual calls