Skip to content

Instantly share code, notes, and snippets.

@bnmrrs
Created June 10, 2014 15:43
Show Gist options
  • Save bnmrrs/ff93241b74c91532a709 to your computer and use it in GitHub Desktop.
Save bnmrrs/ff93241b74c91532a709 to your computer and use it in GitHub Desktop.
module Ledger::Balance
def balance(transaction=nil)
sum_of_credits(transaction) - sum_of_debits(transaction)
end
def amount_available(transaction=nil)
self.balance(transaction)
end
def spent
sum_of_debits
end
protected
def sum_of_credits(transaction=nil)
credits_sum = Ledger::Credit.select('COALESCE(SUM(credit),0) as credit').where(destination: self)
credits_sum = credits_sum.where('transaction_id <= ?', transaction) if transaction
credits_sum.first.credit
end
def sum_of_debits(transaction=nil)
debits_sum = Ledger::Debit.select('COALESCE(SUM(debit),0) as debit').where(destination: self)
debits_sum = credits_sum.where('transaction_id <= ?', transaction) if transaction
debits_sum.first.debit
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment