0

The code below checks and raises a Run Time error for unknown file formats.

def open_spreadsheet
    case File.extname(file.original_filename)
        when ".csv" then CSV.new(file.path)
        when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
        when ".xlsx" then Roo::Excelx.new(file.path)
    else 
        raise "Unknown file type: #{file.original_filename}"
    end
end

I want to show the error message rather than runtime error.

attr_accessor :file

How can I validate the uploaded spreadsheet header field and show the error message if there is any modification in header from standard format?

sawa
  • 165,429
  • 45
  • 277
  • 381
Santosh Aryal
  • 1,276
  • 1
  • 18
  • 41
  • You want to validate the file extension when the user uploads the file. The implementation depends a bit on your controller, model, and library you use for uploads. [Carrierwave](https://github.com/carrierwaveuploader/carrierwave#securing-uploads) for example allows you to define a `extension_whitelist`. If the extension doesn't match the list, the validations fail and the user should see an error. – jdno Dec 17 '18 at 10:29
  • I used accept attributes to accept xls and xlsx for now. – Santosh Aryal Dec 18 '18 at 05:40
  • How do i validate the headers value – Santosh Aryal Dec 18 '18 at 05:40

1 Answers1

0

try something like this:

def open_spreadsheet
    case File.extname self.file.original_filename
    when ".xls"
        Roo::Excel.new self.file.path
    when ".xlsx"
        Roo::Excelx.new self.file.path
    else
        self.errors[:file] << I18n.t("errors.messages.invalid_file_format", extension: File.extname(file.original_filename))
        return nil
    end
end

You could hard-code the message there, but is nice to have it in the correct I18n tag

Alexis
  • 4,836
  • 2
  • 21
  • 27