【译】不要重复你自己:元编程

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/16-dry-metaprogramming

如果你找到一些方法都长得很像,不同的就是方法名称不一样, 或许可以用元编程的方式把这些事情简化

丑陋的...

class Post < ActiveRecord::Base
  validate_inclusion_of :status, :in => ['draft', 'published', 'spam']

def self.all_draft
    find(:all, :conditions => { :status => 'draft' }
  end

def self.all_published
    find(:all, :conditions => { :status => 'published' }
  end

def self.all_spam
    find(:all, :conditions => { :status => 'spam' }
  end

def draft?
    self.status == 'draft'
  end

def published?
    self.status == 'published'
  end

def spam?
    self.status == 'spam'
  end
end

在这个例子中, 这些方法都长得很像,只是名字不同摆了,确切的说只是依赖的状态不同,我们可以用元编程的方式来简化这些代码

重构...

class Post < ActiveRecord::Base

STATUSES = ['draft', 'published', 'spam']
  validate_inclusion_of :status, :in => STATUSES

class < { :status => status_name }
      end
    end

STATUSES.each do |status_name|
      define_method "#{status_name}?" do
         self.status == status_name
      end
    end
  end
end

这样使用元编程来动态生成方法是不是简单干净多了, 除了这个,也更容易去改变, 如果一些状态增加,
修改或者删除,我们只要改变STATUSES这个列表就行了

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top