SoFunction
Updated on 2025-03-04

Example of Ruby using Monkey Patch Monkey patch for program development

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 modify errors in the code when Monkey Patch is zero.

etymology
Monkey patch was first called Guerrilla patch, describing such patches as cunning like guerrillas. Later, it was called Gorilla patch because of its similar pronunciation. Because the gorilla was not cute enough, it was later renamed Monkey patch.

Use scenarios
In my understanding, Monkey patch has two usage scenarios:
Emergency security patch, i.e. Hotfix;
Modify or extend properties and methods in the library.

example:
alias:

class Monkey2 < Monkey 
 def method2 
  puts "This is method2" 
 end 
  
 alias output method2 
end 
 
monkey =  
monkey.method2 
 

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.method1#Because of the duplicate name, the current class method is preferred


undef:

class Monkey 
 def method1 
  puts "This is method1" 
 end 
end  
 
class Monkey2 < Monkey 
 def method2 
  puts "This is method2" 
 end 
end 
 
monkey =  
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 as undef <method_name>, as follows:

class Monkey2 
 remove_method :method1 
 undef_method :method2 
nd 


When using monkey patches, you should also pay attention to the following things:
1. Basically, only functions are added
2. Be cautious when making functional changes and as small as possible
3. Pay attention to mutual calls