Added an Account#path method to get the path of an account, from root to literal...
[fin.git] / accountregister.rb
blob94bc3583acc92414dba9c1a574eb21f12c3456e3
1 require 'account'
3 ################################################################################
4 # A flyweight-factory of _Account_ objects.
5 ################################################################################
6 class AccountRegister
8   def initialize
9       @accounts = {} # all Account objects known
10   end
11   
12   # Open the given account.  If the account doesn't exist, it will be created.
13   # The parameters should be the account's path in the hierarchy.  This method
14   # represents the flyweight factory.
15   #
16   # +account = Account.open('Income', 'Bursaries', 'Uncle Joe')+
17   def open(*path)
18     error = "wrong number of arguments (0 for at least 1)"
19     raise ArgumentError, error if path.empty?
20     account_symbol = path.join('.').to_sym
21     unless @accounts.include? account_symbol # add new account, inform parents
22       parent = path[0..-2].empty? ? nil : open(*path[0..-2])
23       new_account = Account.new(path[-1], parent)
24       new_account.parent.children << new_account unless new_account.parent.nil?
25       @accounts[account_symbol] = new_account
26     end
27     @accounts[account_symbol]
28   end
30   # Check whether the register knows about the given account.
31   def include?(account)
32     @accounts.include? account
33   end
35   # Invoke a block on each account known.
36   def each
37     @accounts.each_value { |account| yield(account) }
38   end
40   # Get the collection of accounts known.
41   def accounts
42     @accounts.values
43   end
44 end