猴子補丁(Monkey Patch)是一種特殊的編程技巧。Monkey patch 可以用來在運行時動態地修改(擴展)類或模塊。我們可以通過添加 Monkey Patch 來修改不滿足自己需求的第三方庫,也可以添加 Monkey Patch 零時修改代碼中的錯誤。
詞源
Monkey patch 最早被稱作 Guerrilla patch,形容這種補丁像游擊隊員一樣狡猾。后來因為發音相似,被稱為 Gorilla patch。因為大猩猩不夠可愛,后改稱為 Monkey patch。
使用場景
以我的理解,Monkey patch 有兩種使用場景:
緊急的安全性補丁,即 Hotfix;
修改或擴展庫中的屬性和方法。
例子:
alias:
1
2
3
4
5
6
7
8
9
10
11
|
class Monkey2 < Monkey def method2 puts "This is method2" end alias output method2 end monkey = Monkey2. new monkey.method2 monkey.output |
include:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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 #因為重名,當前類的方法優先 |
undef:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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 |
我們還可以使用undef_method或者remove_method實現undef <method_name>同樣的功能,例子如下:
1
2
3
4
|
class Monkey2 remove_method :method1 undef_method :method2 nd |
在使用猴子補丁的時候,還應注意如下事項:
1、基本上只追加功能
2、進行功能變更時要謹慎,盡可能的小規模
3、注意相互調用