Sha256: 47d787ca3d9896b61695965dfe61b4f02e6620db0d156a156d957cc89f9b43a2

Contents?: true

Size: 864 Bytes

Versions: 1

Compression:

Stored size: 864 Bytes

Contents

require 'csv'
class Chronicle::ETL::CsvExtractor < Chronicle::ETL::Extractor
  DEFAULT_OPTIONS = {
    headers: true,
    filename: $stdin
  }.freeze

  def initialize(options = {})
    super(DEFAULT_OPTIONS.merge(options))
  end

  def extract
    csv = initialize_csv
    csv.each do |row|
      result = row.to_h
      yield result
    end
  end

  def results_count
    CSV.read(@options[:filename], headers: @options[:headers]).count if read_from_file?
  end

  private

  def initialize_csv
    headers = @options[:headers].is_a?(String) ? @options[:headers].split(',') : @options[:headers]

    csv_options = {
      headers: headers,
      converters: :all
    }

    stream = read_from_file? ? File.open(@options[:filename]) : @options[:filename]
    CSV.new(stream, **csv_options)
  end

  def read_from_file?
    @options[:filename] != $stdin
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
chronicle-etl-0.2.4 lib/chronicle/etl/extractors/csv_extractor.rb