Example of Ruby using Monkey patch Monkey Patches for program development _ruby topics

Source: Internet
Author: User
Tags extend

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.