Skip to content

Extract to composed class

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

Please go to http://rails-bestpractices.com/posts/18-extract-to-composed-class

Before:


# == Schema Information
#  address_city        :string(255)
#  address_street      :string(255)

class Customer < ActiveRecord::Base

  def address_close_to?(other_customer)
    address_city == other_cutomer.address_city
  end

  def address_equal(other_customer)
    address_street == other_customer.address_street &&
      address_city == other_customer.address_city
  end
end

After:


class Customer < ActiveRecord::Base
  composed_of :address, :mapping => [ %w(address_street street), %w(address_city city)]
end

class Address
  attr_reader :street, :city

  def initialize(street, city)
    @street, @city = street, city
  end

  def close_to?(other_address)
    city == other_address.city
  end

  def ==(other_address)
    city == other_address.city && street == other_address.street
  end
end