Sha256: 6dff916f4045f404a0e0948364f17404f9e32c8f1d12acd96da691ae4c417ad6

Contents?: true

Size: 1.05 KB

Versions: 5

Compression:

Stored size: 1.05 KB

Contents

# frozen_string_literal: true

module SmarterCSV
  class << self
    def header_validations(headers, options)
      check_duplicate_headers(headers, options)
      check_required_headers(headers, options)
    end

    def check_duplicate_headers(headers, _options)
      header_counts = Hash.new(0)
      headers.each { |header| header_counts[header] += 1 unless header.nil? }

      duplicates = header_counts.select { |_, count| count > 1 }

      unless duplicates.empty?
        raise(SmarterCSV::DuplicateHeaders, "Duplicate Headers in CSV: #{duplicates.inspect}")
      end
    end

    require 'set'

    def check_required_headers(headers, options)
      if options[:required_keys] && options[:required_keys].is_a?(Array)
        headers_set = headers.to_set
        missing_keys = options[:required_keys].select { |k| !headers_set.include?(k) }

        unless missing_keys.empty?
          raise SmarterCSV::MissingKeys, "ERROR: missing attributes: #{missing_keys.join(',')}. Check `SmarterCSV.headers` for original headers."
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
smarter_csv-1.11.2 lib/smarter_csv/header_validations.rb
smarter_csv-1.11.1 lib/smarter_csv/header_validations.rb
smarter_csv-1.11.0 lib/smarter_csv/header_validations.rb
smarter_csv-1.10.3 lib/smarter_csv/header_validations.rb
smarter_csv-1.10.2 lib/smarter_csv/header_validations.rb