Ruby uses the Monkey Patch Monkey Method for program development example, rubymonkey

Source: Internet
Author: User

Ruby uses the Monkey Patch Monkey Method for program development example, rubymonkey

Monkey Patch is a special programming technique. Monkey patch can be used to dynamically modify (expand) classes or modules at runtime. You can add a Monkey Patch to modify a third-party library that does not meet your needs, or you can add a Monkey Patch to modify errors in the code at zero time.

Source
Monkey patch was first called Guerrilla patch, which described it as a Guerrilla. Later, it was called Gorilla patch because of its similar pronunciation. Because the gorilla is not cute enough, it is later called Monkey patch.

Use Cases
In my understanding, Monkey patch has two application scenarios:
Urgent security patch, that is, Hotfix;
Modify or extend the attributes 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 # The method of the current class takes precedence due to duplicate names


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 implement the same function of undef <method_name>, for example:

class Monkey2  remove_method :method1  undef_method :method2 nd 


When using the monkey Patch, you should also pay attention to the following:
1. basically only append the Function
2. Be cautious when performing function changes and try to make small changes.
3. Pay attention to 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.