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[:ledger_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
147
148
149
150
151
152
153
154
155
156
# File 'lib/reckon/ledger_parser.rb', line 121

def parse(ledger)
  @entries = []
  new_entry = {}
  in_comment = false
  comment_chars = ';#%*|'
  ledger.strip.split("\n").each do |entry|
    # strip comment lines
    in_comment = true if entry == 'comment'
    in_comment = false if entry == 'end comment'
    next if in_comment
    next if entry =~ /^\s*[#{comment_chars}]/

    # (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 entry =~ /^\s*$/ && new_entry[:date]
      add_entry(new_entry)
      new_entry = {}
    elsif new_entry[:date] && entry =~ /^\s+/
      LOGGER.info("Adding new account #{entry}")
      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



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/reckon/ledger_parser.rb', line 159

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