Class: IIF::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/iif/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource) ⇒ Parser

Returns a new instance of Parser.



12
13
14
15
16
17
18
19
20
21
# File 'lib/iif/parser.rb', line 12

def initialize(resource)
  @definitions = {}
  @entries = []
  @transactions = []

  resource = open_resource(resource)
  resource.rewind
  parse_file(resource)
  create_transactions
end

Instance Attribute Details

#definitionsObject

Returns the value of attribute definitions.



8
9
10
# File 'lib/iif/parser.rb', line 8

def definitions
  @definitions
end

#entriesObject

Returns the value of attribute entries.



9
10
11
# File 'lib/iif/parser.rb', line 9

def entries
  @entries
end

#transactionsObject

Returns the value of attribute transactions.



10
11
12
# File 'lib/iif/parser.rb', line 10

def transactions
  @transactions
end

Instance Method Details

#create_transactionsObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/iif/parser.rb', line 66

def create_transactions
  transaction = nil
  in_transaction = false

  @entries.each do |entry|
    
    case entry.type

    when "TRNS"
      if in_transaction
        @transactions.push(transaction)
        in_transaction = false
      end
      transaction = Transaction.new
      in_transaction = true
      
    when "ENDTRNS"
      @transactions.push(transaction)
      in_transaction = false

    end

    transaction.entries.push(entry) if in_transaction
  end
end

#open_resource(resource) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/iif/parser.rb', line 23

def open_resource(resource)
  if resource.respond_to?(:read)
    resource
  else
    open(resource)
  end
rescue Exception
  StringIO.new(resource)
end

#parse_data(fields) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/iif/parser.rb', line 50

def parse_data(fields)
  definition = @definitions[fields[0]]

  entry = Entry.new
  entry.type = fields[0]
  
  fields[1..-1].each_with_index do |field, idx|
    entry.send(definition[idx] + "=", field)
  end

  entry.amount = BigDecimal.new(entry.amount) if entry.amount
  entry.date = Date.strptime(entry.date, "%m/%d/%Y") if entry.date

  @entries.push(entry)
end

#parse_definition(fields) ⇒ Object



44
45
46
47
48
# File 'lib/iif/parser.rb', line 44

def parse_definition(fields)
  key = fields[0][1..-1]
  values = fields[1..-1]
  @definitions[key] = values.map { |v| v.downcase }
end

#parse_file(resource) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/iif/parser.rb', line 33

def parse_file(resource)
  resource.each_line do |line|
    fields = line.strip.split(/\t/)
    if fields[0][0] == '!'
      parse_definition(fields)
    else
      parse_data(fields)
    end
  end
end