我们常常处理这样的代码:
name=person?person.name:nil
   取某个对象的一个属性,先判断对象是否为nil,不是nil就返回对象属性,否则返回nil。这样的代码写多了比较恶心,是否有比较有趣的方式来减少代码?作者给出了一段代码:
module ObjectExtension
def nil_or
 return self unless self.nil?
 o = Object.new
 class << o
   def method_missing(sym, *args); nil; end
 end
 o
 end
end
class Object
 include ObjectExtension
end

  上面的代码为Object加入了扩展,为每个对象实例增加了一个nil_or方法,分析下这个方法:如果对象不为nil,马上返回self(也就是对象本身),否则生成一个新的对象,这个对象通过method_missing机制将所有的方法调用都返回nil(原文是用Class.new,生成的类将不会被GC,这里采用回复给出的方案,生成对象,在对象的metaclass上做method_missing)。那么现在代码可以写成:
   name=person.nil_or.name是不是相当的DSL呢?
Tags:
J2EE开发 | 评论(0) | 引用(0) | 阅读(292)
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
昵称   密码   游客无需密码
网址   电邮   [注册]
               

验证码 不区分大小写