Module: SmarterCSV::HeaderValidations

Included in:
Reader
Defined in:
lib/smarter_csv/header_validations.rb

Instance Method Summary collapse

Instance Method Details

#check_duplicate_headers(headers, _options) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/smarter_csv/header_validations.rb', line 10

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

#check_required_headers(headers, options) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/smarter_csv/header_validations.rb', line 23

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 `reader.headers` for original headers."
    end
  end
end

#header_validations(headers, options) ⇒ Object



5
6
7
8
# File 'lib/smarter_csv/header_validations.rb', line 5

def header_validations(headers, options)
  check_duplicate_headers(headers, options)
  check_required_headers(headers, options)
end