$: << File.dirname(__FILE__)
require "connect"
require "logger"
require "pp"

#ActiveRecord::Base.logger = Logger.new(STDOUT)

#require "rubygems"
#require_gem "activerecord"


#START:lastfive
class LastFive
  
  attr_reader :list

  # Prend une chaine contenant "a,b,c" et la
  # stocke sous la forme [ 'a', 'b', 'c' ]
  def initialize(list_as_string)
    @list = list_as_string.split(/,/)
  end


  # Retourne le contenu sous la forme
  # d'une chaine dont les fragments sont séparés
  # par des virgules
  def last_five
    @list.join(',')
  end
end
#END:lastfive

#START:purchase
class Purchase < ActiveRecord::Base
  composed_of :last_five
end
#END:purchase

Purchase.delete_all

#START:purchasedemo
Purchase.create(:last_five => LastFive.new("3,4,5"))

purchase = Purchase.find(:first)

puts purchase.last_five.list[1]     #=>  4
#END:purchasedemo


#START:name
class Name
  attr_reader :first, :initials, :last

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

  def to_s
    [ @first, @initials, @last ].compact.join(" ")
  end
end
#END:name

#START:customer  
class Customer < ActiveRecord::Base

  composed_of :name,
              :class_name => Name,
              :mapping => 
                 [ # base de données    ruby
                   [ :first_name,  :first ],
                   [ :initials,    :initials ],
                   [ :last_name,   :last ] 
                 ]
end
#END:customer

Customer.delete_all

#START:namedemo
name = Name.new("Dwight", "D", "Eisenhower")

Customer.create(:credit_limit => 1000, :name => name)

customer = Customer.find(:first)
puts customer.name.first    #=> Dwight
puts customer.name.last     #=> Eisenhower
puts customer.name.to_s     #=> Dwight D Eisenhower
customer.name = Name.new("Harry", nil, "Truman")
customer.save
#END:namedemo

