元編程

原文參考: 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 <<self
    STATUSES.each do |status_name|
      define_method "all_#{status_name}" do
        find(:all, :conditions => { :status => status_name }
      end
    end
  end

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

end


嘖嘖

你可能感兴趣的:(编程,Ruby,ActiveRecord,Rails)