Class: Import::CsvDuplicatesValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
app/models/import/csv_duplicates_validator.rb

Overview

CsvDuplicatesValidator

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'app/models/import/csv_duplicates_validator.rb', line 13

def validate(record)
  valid_csv_file = true
  duplicate_id = validate_csv_file(record.csv_file)
  unless duplicate_id.nil?
    valid_csv_file = false
    record.errors.add(:csv_file,
      "Duplicate ID value found: #{duplicate_id}. Please clean up the CSV file and reimport.")
  end

  valid_csv_file
end

#validate_csv_file(csv_file) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/models/import/csv_duplicates_validator.rb', line 25

def validate_csv_file(csv_file)
  ids = Set.new
  duplicate_id = nil
  csv = CSV.parse(csv_file.download, headers: true)

  csv["ID"].each do |id|
    duplicate_id = id unless ids.add?(id)
  end

  duplicate_id
rescue ArgumentError, ActiveStorage::FileNotFoundError
  false
end