class IIF::Parser

Attributes

definitions[RW]
entries[RW]
transactions[RW]

Public Class Methods

new(resource) click to toggle source
# 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

Public Instance Methods

create_transactions() click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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