Sha256: 04e54e991378267df7225fbe347efdd0159c2b9c559888e6758e106a7e939d44

Contents?: true

Size: 868 Bytes

Versions: 9

Compression:

Stored size: 868 Bytes

Contents

# frozen_string_literal: true

require "csv"

# CSV Duplicates Validator
#
# * Checks the CSV file for duplicate IDs.
# * Fails import if duplicate ID is found.
#
class Import
  # CsvDuplicatesValidator
  class CsvDuplicatesValidator < ActiveModel::Validator
    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

    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
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
geoblacklight_admin-0.5.0 app/models/import/csv_duplicates_validator.rb
geoblacklight_admin-0.4.2 app/models/import/csv_duplicates_validator.rb
geoblacklight_admin-0.4.1 app/models/import/csv_duplicates_validator.rb
geoblacklight_admin-0.4.0 app/models/import/csv_duplicates_validator.rb
geoblacklight_admin-0.3.2 app/models/import/csv_duplicates_validator.rb
geoblacklight_admin-0.3.1 app/models/import/csv_duplicates_validator.rb
geoblacklight_admin-0.3.0 app/models/import/csv_duplicates_validator.rb
geoblacklight_admin-0.2.1 app/models/import/csv_duplicates_validator.rb
geoblacklight_admin-0.1.0 app/models/import/csv_duplicates_validator.rb