Ruby使用Monkey Patch猴子补丁方式进行程序开发的示例
猴子补丁(Monkey Patch)是一种特殊的编程技巧。Monkey patch 可以用来在运行时动态地修改(扩展)类或模块。我们可以通过添加 Monkey Patch 来修改不满足自己需求的第三方库,也可以添加 Monkey Patch 零时修改代码中的错误。 词源 使用场景 例子: 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#因为重名,当前类的方法优先
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
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |