create_table :accounts, :force => true do |t|
  t.string :number
  t.decimal :balance, :precision => 10, :scale => 2, :default => 0
end


class Account < ActiveRecord::Base
  validate :price_must_be_at_least_a_cent

  def withdraw(amount)
    adjust_balance_and_save(-amount)
  end

  def deposit(amount)
    adjust_balance_and_save(amount)
  end

private

  def adjust_balance_and_save(amount)
    self.balance += amount
    save!
  end

  def price_must_be_at_least_a_cent
    errors.add(:balance, "je záporná") if balance < 0
  end
end


petr = Account.create(:balance => 100, :number => "12345")
pavel = Account.create(:balance => 200, :number => "54321")

Account.transaction do
  pavel.deposit(10)
  petr.withdraw(10)
end

Account.transaction do
  pavel.deposit(350)
  petr.withdraw(350)
end


begin
  Account.transaction do
    pavel.deposit(350)
    petr.withdraw(350)
  end
rescue
  puts "Přesun zrušen"
end

puts "Pavel má #{pavel.balance}"
puts "Petr má #{petr.balance}"
