customer.rb 2.1 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1
class Customer < ActiveRecord::Base
2 3 4

  cattr_accessor :gps_conversion_was_run

5
  composed_of :address, :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ], :allow_nil => true
6
  composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money }
7
  composed_of :gps_location, :allow_nil => true
8 9
  composed_of :non_blank_gps_location, :class_name => "GpsLocation", :allow_nil => true, :mapping => %w(gps_location gps_location),
              :converter => lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)}
10
  composed_of :fullname, :mapping => %w(name to_s), :constructor => Proc.new { |name| Fullname.parse(name) }, :converter => :parse
D
Initial  
David Heinemeier Hansson 已提交
11 12 13 14 15 16 17 18
end

class Address
  attr_reader :street, :city, :country

  def initialize(street, city, country)
    @street, @city, @country = street, city, country
  end
J
Jeremy Kemper 已提交
19

D
Initial  
David Heinemeier Hansson 已提交
20 21 22
  def close_to?(other_address)
    city == other_address.city && country == other_address.country
  end
23 24 25

  def ==(other)
    other.is_a?(self.class) && other.street == street && other.city == city && other.country == country
J
Jeremy Kemper 已提交
26
  end
D
Initial  
David Heinemeier Hansson 已提交
27 28 29 30
end

class Money
  attr_reader :amount, :currency
J
Jeremy Kemper 已提交
31

D
Initial  
David Heinemeier Hansson 已提交
32
  EXCHANGE_RATES = { "USD_TO_DKK" => 6, "DKK_TO_USD" => 0.6 }
J
Jeremy Kemper 已提交
33

D
Initial  
David Heinemeier Hansson 已提交
34 35 36
  def initialize(amount, currency = "USD")
    @amount, @currency = amount, currency
  end
J
Jeremy Kemper 已提交
37

D
Initial  
David Heinemeier Hansson 已提交
38 39 40
  def exchange_to(other_currency)
    Money.new((amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor, other_currency)
  end
41 42 43 44
end

class GpsLocation
  attr_reader :gps_location
J
Jeremy Kemper 已提交
45

46 47 48
  def initialize(gps_location)
    @gps_location = gps_location
  end
J
Jeremy Kemper 已提交
49

50 51 52
  def latitude
    gps_location.split("x").first
  end
J
Jeremy Kemper 已提交
53

54 55 56
  def longitude
    gps_location.split("x").last
  end
57 58 59 60

  def ==(other)
    self.latitude == other.latitude && self.longitude == other.longitude
  end
61
end
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

class Fullname
  attr_reader :first, :last

  def self.parse(str)
    return nil unless str
    new(*str.to_s.split)
  end

  def initialize(first, last = nil)
    @first, @last = first, last
  end

  def to_s
    "#{first} #{last.upcase}"
  end
78
end