当前位置: 移动技术网 > IT编程>脚本编程>Ruby > Ruby使用Monkey Patch猴子补丁方式进行程序开发的示例

Ruby使用Monkey Patch猴子补丁方式进行程序开发的示例

2017年12月01日  | 移动技术网IT编程  | 我要评论
猴子补丁(monkey patch)是一种特殊的编程技巧。monkey patch 可以用来在运行时动态地修改(扩展)类或模块。我们可以通过添加 monkey patch

猴子补丁(monkey patch)是一种特殊的编程技巧。monkey patch 可以用来在运行时动态地修改(扩展)类或模块。我们可以通过添加 monkey patch 来修改不满足自己需求的第三方库,也可以添加 monkey patch 零时修改代码中的错误。

词源
monkey patch 最早被称作 guerrilla patch,形容这种补丁像游击队员一样狡猾。后来因为发音相似,被称为 gorilla patch。因为大猩猩不够可爱,后改称为 monkey patch。

使用场景
以我的理解,monkey patch 有两种使用场景:
紧急的安全性补丁,即 hotfix;
修改或扩展库中的属性和方法。

例子:
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 


在使用猴子补丁的时候,还应注意如下事项:
1、基本上只追加功能
2、进行功能变更时要谨慎,尽可能的小规模
3、注意相互调用

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网