Sha256: 4f4e0996e77f2bcd5e7f557faddf426940d9bb1879f8a1d029e7d95c428b76d8

Contents?: true

Size: 1.27 KB

Versions: 7

Compression:

Stored size: 1.27 KB

Contents

require 'csv'
require 'fileutils'

module Forklift
  module Connection
    class Csv < Forklift::Base::Connection

      def initialize(config, forklift)
        @config = config
        @forklift = forklift
      end

      def config
        @config
      end

      def forklift
        @forklift
      end

      def read(size=1000)
        data = []
        CSV.foreach(config[:file], headers: true, converters: :all) do |row|
          data << row.to_hash.symbolize_keys
          if(data.length == size)
            if block_given?
              yield data
              data = []
            else
              return data
            end
          end
        end

        if block_given?
          yield data
        else
          return data
        end
      end

      def write(data, append=true)
        if (append == false)
          FileUtils.rm(config[:file], {force: true})
        end

        if( !File.exists?(config[:file]) )
          keys = data.first.keys
          row = {}
          keys.each do |k|
            row[k] = k
          end
          data = [row] + data
        end

        CSV.open(config[:file],'a') do |file|
          data.each do |row|
            file << row.values
          end
        end

      end

      private

      #/private

    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
forklift_etl-1.1.8 lib/forklift/transports/csv.rb
forklift_etl-1.1.7 lib/forklift/transports/csv.rb
forklift_etl-1.1.6 lib/forklift/transports/csv.rb
forklift_etl-1.1.5 lib/forklift/transports/csv.rb
forklift_etl-1.1.4 lib/forklift/transports/csv.rb
forklift_etl-1.1.3 lib/forklift/transports/csv.rb
forklift_etl-1.1.2 lib/forklift/transports/csv.rb