Ruby之猴子补丁
何谓猴子补丁(Monkey Patch)?在动态语言中,不修改源代码而对功能进行追加和变更。
使用猴子补丁的目的:
1、追加功能
2、功能变更
3、修正程序错误
4、增加钩子,在执行某个方法的同时执行一些其他的处理,如打印日志,实现AOP等,
5、缓存,在计算量很大,结算之后的结果可以反复使用的情况下,在一次计算完成之后,对方法进行替换可以提高处理速度。
Ruby的类都是开放类,即在类定义之后还可以任意添加内容, 这就使得在Ruby中使用猴子补丁变得特别容易了。另外,Ruby还提供了对方法、类和模块的进行操作的功能,让我们使用猴子补丁更加得心应手。Ruby提供的基本功能如下:
alias:给方法另起别名
include:引入其他模块的方法
remove_method: 取消本类中的方法
undef:取消方法
例子:
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#因为重名,当前类的方法优先
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
我们还可以使用undef_method或者remove_method实现undef <method_name>同样的功能,例子如下:
- class Monkey2
- remove_method :method1
- undef_method :method2
- nd
猴子补丁是一个非常诱人的功能,尤其是在java的那个改个标点符号都要重新编译、打包的世界。因此,老衲内心十分的喜欢,分享给大家,但是剑有双刃,如若使用不当,也会伤着自己。因此在使用猴子补丁的时候,还应注意如下事项:
1、基本上只追加功能
2、进行功能变更时要谨慎,尽可能的小规模
3、注意相互调用

浙公网安备 33010602011771号