Skip to content

Instantly share code, notes, and snippets.

@sprite2005
Created February 17, 2009 21:48
Show Gist options
  • Save sprite2005/66009 to your computer and use it in GitHub Desktop.
Save sprite2005/66009 to your computer and use it in GitHub Desktop.
class TransactionAccount < ActiveRecord::Base
composed_of :balance, :class_name => "Money", :mapping => [%w(account_balance_cents cents), %w(currency currency) ]
belongs_to :user
has_many :sent_transactions, :class_name => "TransactionItem",
:foreign_key => "transaction_sender_account_id"
has_many :received_transactions, :class_name => "TransactionItem",
:foreign_key => "transaction_receiver_account_id"
def transactions
TransactionItem.find(:all, :conditions => ["transaction_sender_account_id = ? OR transaction_receiver_account_id = ?",id,id])
end
def update_balance
calculated_balance = Money.new(0, "USD")
sent_transactions.each do |transaction|
calculated_balance += transaction.sender_calculate
end
received_transactions.each do |transaction|
calculated_balance += transaction.receiver_calculate
end
self.balance = calculated_balance
save
end
end
class TransactionItem < ActiveRecord::Base
VALID_TRANSACTION_STATUS = ["Pending", "Complete"]
composed_of :amount, :class_name => "Money", :mapping => [%w(cents cents), %w(currency currency) ]
belongs_to :sender,
:class_name => "TransactionAccount",
:foreign_key => "transaction_sender_account_id"
belongs_to :receiver,
:class_name => "TransactionAccount",
:foreign_key => "transaction_receiver_account_id"
belongs_to :transaction_object,
:polymorphic => true
validates_presence_of :description
validates_inclusion_of :status, :in => VALID_TRANSACTION_STATUS
# Used to update a transaction, for example a call that is in progress
def update
end
# Used to finalize a transaction, for example when a call is completed
def finalize
end
# Amount the receiver gets
def receiver_amount
Money.new(0)
end
# Amount the sender gets
def sender_amount
Money.new(0)
end
# Defines the behaviour of this item when calculating account totals
def receiver_calculate
Money.new(0)
end
# Defines the behaviour of this item when calculating account totals
def sender_calculate
Money.new(0)
end
private
validate :cents_not_zero
def cents_not_zero
errors.add("cents", "cannot be zero or less") unless cents > 0
end
end
class TransactionItemDeposit < TransactionItem
validates_presence_of :receiver
def initialize(account, amount, description)
super()
self.receiver = account
self.amount = Money.new(amount, "USD")
self.status = "Pending"
description.nil? ? self.description = "Deposit" : self.description = description
end
def receiver_amount
amount
end
def receiver_calculate
case status
when "Pending"
Money.new(0, "USD")
when "Complete"
amount
end
end
def finalize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment