Skip to content

Commit

Permalink
Don't rewind to the beginning, look for the header, if found, set it,…
Browse files Browse the repository at this point in the history
… if not, we are at the first record.
  • Loading branch information
jscipione committed Nov 23, 2010
1 parent c0c8e83 commit 3de42c4
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions lib/qif/reader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ module Qif
# end
class Reader
include Enumerable

# Create a new Qif::Reader object. The data argument must be
# either an IO object or a String containing the Qif file data.
#
Expand All @@ -25,7 +25,6 @@ def initialize(data, format = 'dd/mm/yyyy')
@format = DateFormat.new(format)
@data = data.respond_to?(:read) ? data : StringIO.new(data.to_s)
read_header
rewind
reset
end

Expand All @@ -36,7 +35,7 @@ def transactions
read_all_transactions
transaction_cache
end

# Call a block with each Qif::Transaction from the Qif file. This
# method yields each transaction as it reads the file so it is better
# to use this than #transactions for large qif files.
Expand All @@ -46,29 +45,29 @@ def transactions
# end
def each(&block)
reset

while transaction = next_transaction
yield transaction
end
end

# Return the number of transactions in the qif file.
def size
read_all_transactions
transaction_cache.size
end
alias length size

private

def read_all_transactions
while next_transaction; end
end

def transaction_cache
@transaction_cache ||= []
end

def reset
@index = -1
end
Expand All @@ -79,25 +78,33 @@ def rewind

def next_transaction
@index += 1

if transaction = transaction_cache[@index]
transaction
else
read_transaction
end
end

def read_header
@header = read_record
begin
line = @data.readline
end until line =~ /^!/ || line =~ /^\w/

if line =~ /^!/
@header = line[1..-1].strip
else
@header = ''
end
end

def read_transaction
if record = read_record
transaction = Transaction.read(record)
cache_transaction(transaction) if transaction
end
end

def cache_transaction(transaction)
transaction_cache[@index] = transaction
end
Expand All @@ -110,12 +117,12 @@ def read_record
key = line[0,1]

record[key] = line[1..-1].strip

if date = @format.parse(record[key])
record[key] = date
end
end until line =~ /^\^/

record
rescue EOFError => e
@data.close
Expand Down

0 comments on commit 3de42c4

Please sign in to comment.