Class: Teri::Ledger

Inherits:
Object
  • Object
show all
Defined in:
lib/teri/ledger.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, file_adapter = nil) ⇒ Ledger

Initialize a new Ledger with a file path

Parameters:

  • file (String)

    Path to the ledger file

  • file_adapter (FileAdapter) (defaults to: nil)

    Optional file adapter for testing



11
12
13
14
15
16
# File 'lib/teri/ledger.rb', line 11

def initialize(file, file_adapter = nil)
  @file = file
  @transactions_data = []
  @file_adapter = file_adapter || Teri::FileAdapter.new
  parse_file
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



6
7
8
# File 'lib/teri/ledger.rb', line 6

def file
  @file
end

#transactions_dataObject (readonly)

Returns the value of attribute transactions_data.



6
7
8
# File 'lib/teri/ledger.rb', line 6

def transactions_data
  @transactions_data
end

Class Method Details

.parse(file, file_adapter = nil) ⇒ Ledger

Parse a ledger file and return a Ledger object

Parameters:

  • file (String)

    Path to the ledger file

  • file_adapter (FileAdapter) (defaults to: nil)

    Optional file adapter for testing

Returns:

  • (Ledger)

    Ledger object with parsed transactions



28
29
30
# File 'lib/teri/ledger.rb', line 28

def self.parse(file, file_adapter = nil)
  new(file, file_adapter)
end

.parse_account_line(line) ⇒ Array<String, Float>

Parse an account line into account and amount

Parameters:

  • line (String)

    Account line

Returns:

  • (Array<String, Float>)

    Account name and amount



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/teri/ledger.rb', line 35

def self.(line)
  # Try to match the line against different formats

  # Format: "    Account  $Amount"
  if line =~ /^\s*(.+?)\s+\$([\-\d,\.]+)(?:\s+[A-Z]+)?$/
     = ::Regexp.last_match(1).strip
    amount = ::Regexp.last_match(2).delete(',').to_f
    return [, amount]
  end

  # Format: "    Account  -$Amount"
  if line =~ /^\s*(.+?)\s+-\$([\d,\.]+)(?:\s+[A-Z]+)?$/
     = ::Regexp.last_match(1).strip
    amount = -::Regexp.last_match(2).delete(',').to_f
    return [, amount]
  end

  # Format: "    Account  Amount USD"
  if line =~ /^\s*(.+?)\s+([\-\d,\.]+)\s+USD$/
     = ::Regexp.last_match(1).strip
    amount = ::Regexp.last_match(2).delete(',').to_f
    return [, amount]
  end

  # If no amount found, just return the account
  [line.strip, nil]
end

Instance Method Details

#transactionsArray<Hash>

Get the transactions from the ledger

Returns:

  • (Array<Hash>)

    Array of transaction hashes



20
21
22
# File 'lib/teri/ledger.rb', line 20

def transactions
  @transactions_data
end