Fork me on GitHub

Extract into Module

24 Jul 2010

Wen-Tien Chang (ihower@gmail.com)

It is not exactly a code smell, it is an improvement.

Before Refactor

class User < ActiveRecord::Base
  validates_presence_of :cellphone
  before_save :parse_cellphone

  def parse_cellphone
    # do something
  end
end

As you see, User model has a presence validation of cellphone and a before save callback parse_cellphone, they are related and can be abstracted into a module.

After Refactor

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

Now we extract the cellphone related validation and callback into the HasCellphone module, so we can only include HasCellphone module in User model to add the ability of validation and callback.

Tags