An example of Ruby using Monkey Patch monkey patches for program development

Time:2019-4-18

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

Recommended Today

PHP 12th week function learning record

sha1() effect sha1()Function to evaluate the value of a stringSHA-1Hash. usage sha1(string,raw) case <?php $str = “Hello”; echo sha1($str); ?> result f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0 sha1_file() effect sha1_file()Function calculation fileSHA-1Hash. usage sha1_file(file,raw) case <?php $filename = “test.txt”; $sha1file = sha1_file($filename); echo $sha1file; ?> result aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d similar_text() effect similar_text()Function to calculate the similarity between two strings. usage similar_text(string1,string2,percent) case […]