Class: ImportableAttachments::CsvValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
app/validators/importable_attachments/csv_validator.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object

:call-seq: validate :record

ensures that the record’s attachment file name has a .xls extension



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/validators/importable_attachments/csv_validator.rb', line 12

def validate(record)
  extension = record.attachment.io_stream_file_name.split('.').last
  if extension.downcase != 'csv'
    record.errors.add :attachment, 'invalid attachment'
    record.attachment.errors.add :base, 'File must be a CSV (.csv) file'
  end

  if defined? FasterCSV
    begin
      FasterCSV.read record.attachment.io_stream
    rescue FasterCSV::MalformedCSVError => err
      record.errors.add :attachment, 'invalid attachment'
      record.attachment.errors.add :base, err.messages.join(', ')
    end
  else
    begin
      CSV.read record.attachment.io_stream.path
    rescue CSV::MalformedCSVError => err
      record.errors.add :attachment, 'invalid attachment'
      record.attachment.errors.add :base, err.messages.join(', ')
    end
  end
end