Monkey Patch is a special programming technique. Monkey patch can be used to dynamically modify (extend) classes or modules at runtime. We can modify third-party libraries that do not meet our needs by adding Monkey Patch, or we can add Monkey Patch to modify errors in code at zero time.
etymology
Monkey patch was first called Guerrilla patch, describing patches as cunning as guerrillas. Later, because of similar pronunciation, it was called Gorilla patch. Because the gorillas were not cute enough, they were later renamed Monkey patch.
Usage scenarios
As I understand it, Monkey patch has two usage scenarios:
Emergency security patch, Hotfix;
Modify or extend attributes and methods in libraries.
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
end
class Monkey
include Helper
def method1
puts "monkey method1..."
end
end
monkey = Monkey.new
monkey.help
Monkey. method1 # Because of rename, the method of the current class takes precedence.
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 achieve the same function as undef <method_name>, as shown below:
class Monkey2
remove_method :method1
undef_method :method2
nd
When using the monkey patch, the following points should also be noted:
1. Basically, only additional functions
2. Be cautious when making functional changes and try to be as small as possible.
3. Pay attention to calling each other