`

动态生成Proc,看了一篇名为The Methodphitamine 的文章

    博客分类:
  • Ruby
阅读更多

这篇文章中,采用了对to_proc hack的方式实现了一种更加自然语言的方式来编程,例如:

 ruby 代码

  1. File.read("/etc/passwd").split.sort_by &it.split(":")[2]   
  2. User.find(:all).map &its.contacts.map(&its.last_name.capitalize)  

hack的过程,让我们来看下面的代码:

ruby 代码
  1. module Kernel   
  2.   protected   
  3.   def it() It.new end  
  4.   alias its it   
  5. end  
  6.   
  7. class It   
  8.   
  9.   undef_method(*(instance_methods - %w*__id__ __send__*))   
  10.   
  11.   def initialize   
  12.     @methods = []   
  13.   end  
  14.   
  15.   def method_missing(*args, &block)   
  16.     @methods << [args, block] unless args == [:respond_to?, :to_proc]   
  17.     self  
  18.   end  
  19.   
  20.   def to_proc   
  21.     lambda do |obj|   
  22.       @methods.inject(obj) do |current,(args,block)|   
  23.         current.send(*args, &block)   
  24.       end  
  25.     end  
  26.   end  
  27. end  

可以看到,作者主要利用了method_missing来实现他的小把戏,重写了to_proc来动态生成Proc对象,生成了一个动态的调用链。很酷。

要是愿意,我们也可以在Kernel中定义更多的alias,譬如he,his,she,her,这样,可以实现类似于

ruby 代码
  1. User.find(:all).collect &his.name.collect &its.firstname.capitalize  

这样非常口语化的代码

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics