ruby-on-railsexceptionroo

rails spreadsheet processing and exceptions


In my rails app I am using Roo to process spreadsheet and I want to handle TypeError exception if the file is not a spreadsheet.

begin
  xls = Roo::Excelx.new(@file_upload.file.path)       
rescue TypeError
  return redirect_to students_url, :flash => { :error => t("wrong_file_format") } 
end

How do I add a case that also tries if the file is an open office?

xls = Roo::OpenOffice.new(@file_upload.file.path)

Solution

  • This can be done conveniently by basing the decision on the file extension.

    begin
      case File.extname(file_path = @file_upload.file.path) # file's extension
        when ".xlsx" # excel extension
          xls = Roo::Excelx.new(file_path)
        when ".ods" # openoffice extension
          xls = Roo::OpenOffice.new(file_path)
        else
          raise TypeError
      end
    rescue TypeError
      return redirect_to students_url, flash: {error: t("wrong_file_format")}
    end
    

    I hope I got the extensions right. If not, you can easily modify them in the code.