Module: DoubleEntry::BalanceCalculator

Extended by:
BalanceCalculator
Included in:
BalanceCalculator
Defined in:
lib/double_entry/balance_calculator.rb

Defined Under Namespace

Classes: Options, RelationBuilder

Instance Method Summary collapse

Instance Method Details

#calculate(account, args = {}) ⇒ Money

Get the current or historic balance of an account.

Parameters:

  • account (DoubleEntry::Account:Instance)
  • args (Hash) (defaults to: {})

    a customizable set of options

Options Hash (args):

  • :from (Time)
  • :to (Time)
  • :at (Time)
  • :code (Symbol)
  • :codes (Array<Symbol>)

Returns:

  • (Money)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/double_entry/balance_calculator.rb', line 16

def calculate(, args = {})
  options = Options.new(, args)
  relations = RelationBuilder.new(options)
  lines = relations.build

  if options.between? || options.code?
    # from and to or code lookups have to be done via sum
    Money.new(lines.sum(:amount), .currency)
  else
    # all other lookups can be performed with running balances
    result = lines.
             from(lines_table_name(options)).
             order('id DESC').
             limit(1).
             pluck(:balance)
    result.empty? ? Money.zero(.currency) : Money.new(result.first, .currency)
  end
end