Class: Qif::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/qif/writer.rb

Overview

The Qif::Writer class takes Qif::Transaction objects and outputs a Qif file.

Usage:

Qif::Writer.open('/path/to/new/qif') do |writer|
  writer << Qif::Transaction.new(
    :date => Time.now, 
    :amount => 10.0, 
    :name => 'Credit'
  )
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, type = 'Bank', format = 'dd/mm/yyyy') ⇒ Writer

Create a new Qif::Writer. Expects an IO object or a filepath. Can optionally take a block which will yield the writer and automatically call write afterwards.

Parameters:

  • io - An IO object or filepath

  • type - Used to write the header, defaults to ‘Bank’

  • format - The format of dates in the qif file, defaults to ‘dd/mm/yyyy’. Also accepts ‘mm/dd/yyyy’

Usage:

buffer = StringIO.new
writer = Qif::Writer.new(buffer)
writer << Qif::Transaction.new(:date => Time.now, :amount => 10.0, :name => 'Credit')
writer.write
puts buffer

Usage with block:

buffer = StringIO.new
Qif::Writer.new(buffer) do |writer|
  writer << Qif::Transaction.new(:date => Time.now, :amount => 10.0, :name => 'Credit')
end
puts buffer


50
51
52
53
54
55
56
57
58
59
60
# File 'lib/qif/writer.rb', line 50

def initialize(io, type = 'Bank', format = 'dd/mm/yyyy')
  @io = io.respond_to?(:write) ? io : File.open(io, 'w')
  @type = type
  @format = format
  @transactions = []
  
  if block_given?
    yield self
    self.write
  end
end

Instance Attribute Details

#formatObject

Returns the value of attribute format.



17
18
19
# File 'lib/qif/writer.rb', line 17

def format
  @format
end

#typeObject

Returns the value of attribute type.



17
18
19
# File 'lib/qif/writer.rb', line 17

def type
  @type
end

Class Method Details

.open(path, type = 'Bank', format = 'dd/mm/yyyy', &block) ⇒ Object

Open a qif file for writing and yield a Qif::Writer instance. For parameters see #new.



21
22
23
24
25
# File 'lib/qif/writer.rb', line 21

def self.open(path, type = 'Bank', format = 'dd/mm/yyyy', &block)
  File.open(path, 'w') do |file|
    self.new(file, type, format, &block)
  end
end

Instance Method Details

#<<(transaction) ⇒ Object

Add a transaction for writing



63
64
65
# File 'lib/qif/writer.rb', line 63

def <<(transaction)
  @transactions << transaction
end

#closeObject

Close the qif file



74
75
76
# File 'lib/qif/writer.rb', line 74

def close
  @io.close
end

#writeObject

Write the qif file



68
69
70
71
# File 'lib/qif/writer.rb', line 68

def write
  write_header
  write_transactions
end