Extract into Module


有些代碼我們可以把它們提取出來,這可以方便我們重用這部分代碼.如下面這段:
原文參考: http://rails-bestpractices.com/posts/17-extract-into-module

重構前:
class User < ActiveRecord::Base
  validates_presence_of :cellphone
  before_save :parse_cellphone

  def parse_cellphone
    # do something
  end
end


重構后:
module HasCellphone
  def self.included(base)
    base.validates_presence_of :cellphone
    base.before_save :parse_cellphone
  end

  def parse_cellphone
    # do something
  end
end

class User < ActiveRecord::Base
  include HasCellphone
end

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