Sha256: a81b81a5373d5dc2230b1f3e49697b2f8ee77877fba7359db6fc0436fe80abd4

Contents?: true

Size: 964 Bytes

Versions: 40

Compression:

Stored size: 964 Bytes

Contents

require 'arc-furnace/sink'

module ArcFurnace
  class FixedColumnCSVSink < Sink
    private_attr_reader :fields, :csv

    # Expects filename to a filename to open the csv
    # Expects fields to a hash of Column name => column count
    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

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

    def finalize
      csv.close
    end

    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
  end
end

Version data entries

40 entries across 40 versions & 1 rubygems

Version Path
arc-furnace-0.1.42 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.41 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.40 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.39 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.38 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.37 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.36 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.35 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.34 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.33 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.32 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.31 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.30 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.29 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.28 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.27 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.26 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.25 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.24 lib/arc-furnace/fixed_column_csv_sink.rb
arc-furnace-0.1.23 lib/arc-furnace/fixed_column_csv_sink.rb