Monkey Patch (Monkey Patch) is a special programming technique. Monkey patch can be used to dynamically modify (extend) A class or module at run time. We can modify the Third-party libraries that do not meet our needs by adding monkey Patch, or you can modify errors in the code by adding monkey Patch zero.
Etymology
Monkey Patch, the earliest known as guerrilla patch, described the patch as cunning as a guerrilla. Later, because of the similar pronunciation, is called Gorilla patch. Because the gorilla is not cute enough, then renamed Monkey Patch.
Working with scenes
as I understand it, there are two monkey patch use scenarios:
Emergency security patch, IE Hotfix;
Modify or extend the properties 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# Because of the duplicate name, the current class method takes precedence
Undef
Class Monkey
def method1
puts ' This is method1 '
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 achieve the same function as undef <method_name>, examples are as follows:
Class Monkey2
remove_method:method1
undef_method:method2
nd
When you use monkey patches, you should also note the following:
1, basically append functionality only
2, be cautious when making functional changes, as small as possible
3, note mutual calls