Skip to content

Extract into Module

Richard Huang edited this page Aug 15, 2010 · 4 revisions

Please go to http://rails-bestpractices.com/posts/17-extract-into-module

Before:


class User < ActiveRecord::Base

  validates_presence_of :cellphone
  before_save :parse_cellphone

  def parse_cellphone
    # do something
  end

end

After:


module HasCellphone

  def self.included(base)
    base.validates_presence_of :cellphone
    base.before_save :parse_cellphone

    base.send(:include, InstanceMethods)
    base.send(:extend, ClassMethods)
  end

  module InstanceMethods
    def parse_cellphone
      # do something
    end
  end

  module ClassMethod
  end

end

class User < ActiveRecord::Base
  include HasCellphone
end