Class: ArcFurnace::FixedColumnCSVSink

Inherits:
Sink
  • Object
show all
Defined in:
lib/arc-furnace/fixed_column_csv_sink.rb

Direct Known Subclasses

SuffixedFixedColumnCSVSink

Instance Method Summary collapse

Methods inherited from Sink

#prepare

Constructor Details

#initialize(filename:, fields:, encoding: 'UTF-8', force_quotes: false) ⇒ FixedColumnCSVSink

Expects filename to a filename to open the csv Expects fields to a hash of Column name => column count



9
10
11
12
13
# File 'lib/arc-furnace/fixed_column_csv_sink.rb', line 9

def initialize(filename: , fields: , encoding: 'UTF-8', force_quotes: false)
  @csv = CSV.open(filename, 'wb', encoding: encoding, headers: true, force_quotes: force_quotes)
  @fields = fields
  write_header
end

Instance Method Details

#finalizeObject



21
22
23
# File 'lib/arc-furnace/fixed_column_csv_sink.rb', line 21

def finalize
  csv.close
end

#row(hash) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/arc-furnace/fixed_column_csv_sink.rb', line 25

def row(hash)
  row = []
  fields.each do |column_name, count|
    values = Array.wrap(hash[column_name])
    (values.slice(0, count) || []).each do |value|
      row << value
    end
    (count - values.length).times { row << nil }
  end
  csv << row
end

#write_headerObject



15
16
17
18
19
# File 'lib/arc-furnace/fixed_column_csv_sink.rb', line 15

def write_header
  csv << fields.each_with_object([]) do |(key, count), result|
    count.times { result << key }
  end
end