Class: Reckon::BeancountParser

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ BeancountParser

Returns a new instance of BeancountParser.



9
10
11
12
# File 'lib/reckon/beancount_parser.rb', line 9

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

Instance Attribute Details

#entriesObject

Returns the value of attribute entries.



7
8
9
# File 'lib/reckon/beancount_parser.rb', line 7

def entries
  @entries
end

Instance Method Details

#format_row(row, line1, line2) ⇒ Object



67
68
69
70
71
72
# File 'lib/reckon/beancount_parser.rb', line 67

def format_row(row, line1, line2)
  out = %Q{#{row[:pretty_date]} * "#{row[:description]}" "#{row[:note]}"\n}
  out += "\t#{line1.first}\t\t\t#{line1.last}\n"
  out += "\t#{line2.first}\t\t\t#{line2.last}\n\n"
  out
end

#parse(input) ⇒ Object

input is an object that response to #each_line, (i.e. a StringIO or an IO object)



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
62
63
64
65
# File 'lib/reckon/beancount_parser.rb', line 20

def parse(input)
  entries = []
  comment_chars = ';#%*|'
  new_entry = {}

  input.each_line do |entry|

    next if entry =~ /^\s*[#{comment_chars}]/

    m = entry.match(%r{
      ^
      (\d+[\d/-]+)  # date
      \s+
      ([*!])? # type
      \s*
      ("[^"]*")? # description (optional)
      \s*
      ("[^"]*")? # notes (optional)
      # tags (not implemented)
    }x)

    # (date, type, code, description), type and code are optional
    if (m)
      add_entry(entries, new_entry)
      new_entry = {
        date: try_parse_date(m[1]),
        type: m[2] || "",
        desc: trim_quote(m[3]),
        notes: trim_quote(m[4]),
        accounts: []
      }
    elsif entry =~ /^\s*$/ && new_entry[:date]
      add_entry(entries, 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(entries, new_entry)
      new_entry = {}
    end

  end
  entries
end