Sha256: 27277d5149fc6d9e7be07498e32c5c905003488fc1a4a62c6b012d6036a08c10

Contents?: true

Size: 980 Bytes

Versions: 3

Compression:

Stored size: 980 Bytes

Contents

require 'csv'

module Itiel
  module Load
    #
    # Loads the data stream into a CSV file
    #
    # Usage:
    #
    #     @csv_file = Itiel::Load::CSVFile.new('filename.csv')
    #     @csv_file.input = []
    #
    class CSVFile
      include ChainedStep
      include Itiel::Nameable

      def initialize(file_name, append=true)
        @append    = append
        @file_name = file_name
      end

      def persist(input_stream)
        headers = input_stream.collect(&:keys).flatten.uniq
        mode    = @append ? "ab" : "w"
        skip_headers = skip_headers?

        CSV.open(@file_name, mode) do |csv|
          csv << headers unless skip_headers
          input_stream.each do |row|
            csv_row = []
            headers.each do |h|
              csv_row << row[h]
            end
            csv << csv_row
          end
        end
      end

      private
      def skip_headers?
        File.exist?(@file_name) && @append
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
itiel-0.1.2 lib/itiel/load/csv_file.rb
itiel-0.1.1 lib/itiel/load/csv_file.rb
itiel-0.1.0 lib/itiel/load/csv_file.rb