Class: Reckon::LedgerParser

Inherits:
Object
  • Object
show all
Defined in:
lib/reckon/ledger_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ledger, options = {}) ⇒ LedgerParser

Returns a new instance of LedgerParser.



115
116
117
118
119
# File 'lib/reckon/ledger_parser.rb', line 115

def initialize(ledger, options = {})
  @options = options
  @date_format = options[:date_format] || '%Y-%m-%d'
  parse(ledger)
end

Instance Attribute Details

#entriesObject

Returns the value of attribute entries.



113
114
115
# File 'lib/reckon/ledger_parser.rb', line 113

def entries
  @entries
end

Instance Method Details

#parse(ledger) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/reckon/ledger_parser.rb', line 121

def parse(ledger)
  @entries = []
  new_entry = {}
  ledger.strip.split("\n").each do |entry|
    next if entry =~ /^\s*$/ || entry =~ /^\s*;/

    # (date, type, code, description), type and code are optional
    if (m = entry.match(%r{^(\d+[\d/-]+)\s+([*!])?\s*(\([^)]+\))?\s*(.*)$}))
      add_entry(new_entry)
      new_entry = {
        date: try_parse_date(m[1]),
        type: m[2] || "",
        code: m[3] && m[3].tr('()', '') || "",
        desc: m[4].strip,
        accounts: []
      }
    elsif new_entry[:date] && entry =~ /^\s+/
      new_entry[:accounts] << (entry)
    else
      LOGGER.info("Unknown entry type: #{entry}")
      add_entry(new_entry)
      new_entry = {}
    end
  end
  add_entry(new_entry)
end

#to_csvObject

roughly matches ledger csv format



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/reckon/ledger_parser.rb', line 149

def to_csv
  return @entries.flat_map do |n|
    n[:accounts].map do |a|
      row = [
        n[:date].strftime(@date_format),
        n[:code],
        n[:desc],
        a[:name],
        "", # currency (not implemented)
        a[:amount],
        n[:type],
        "", # account comment (not implemented)
      ]
      CSV.generate_line(row).strip
    end
  end
end