Class: ActiveModel::Validations::CsvValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/activemodel/validations/csv_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/activemodel/validations/csv_validator.rb', line 8

def validate_each(record, attribute, value)
  return if value.nil?

  content = NKF.nkf('-w', File.read(value.path, universal_newline: true))
  rows = CSV.parse(content, headers: :first_row, converters: :integer)

  if options[:max].present? && rows.size > options[:max]
    record.errors.add(attribute, :max_rows, **options.slice(:max).merge(rows: rows.size))
  end

  if options[:min].present? && rows.size < options[:min]
    record.errors.add(attribute, :min_rows, **options.slice(:min).merge(rows: rows.size))
  end

  if options[:headers].present?
    headers = options[:headers].respond_to?(:call) ? options[:headers].call(record) : options[:headers]
    missing_headers = headers - rows.headers
    if missing_headers.present?
      record.errors.add(attribute, :missing_headers, missing_headers: missing_headers.to_sentence)
    end
  end
rescue CSV::MalformedCSVError
  record.errors.add(attribute, :invalid_csv)
end