Open a remote file with Roo gem uploaded using Active Storage on Heroku and Amazon S3

1.3k views Asked by At

I am using the ROO gem to parse an Excel file uploaded by the user (Active Storage with AWS S3) on Heroku.

Since I am on Heroku I cannot download it on filesystem and then parse it. How can I open it from HTTP?

Model

class Report < ApplicationRecord
  has_one_attached :search_report


def parsing_method(path_http)

   xlsx = Roo::Spreadsheet.open(path_http)
end 
4

There are 4 answers

0
Zavitoski On

In a similar application, I used this:

def parsing_method(path_http)

   xlsx = Roo::Excelx.new(path_http, nil, :ignore)

end 

It should work for you.

0
estani On

Yes, you can download it in Heroku into the filesystem.

I doubt theres much space, but you should be able to use the temp file. Most system stores an upload into the temp file system before pushing it somewhere else.

I'm already doing it, since Roo was patch to be able to open Excel files from the stream, but no other type (csv, ods, etc).

def create_temp_file
  filename = some_model.some_attachment.blob.filename
  @tmp = Tempfile.new([filename.base, filename.extension_with_delimiter], binmode: true)
  @tmp.write(ome_model.some_attachment.download)
  @tmp.rewind
  @tmp
end

# this is how you use it, note the rescue part
def access_the_file
  spreadsheet = Roo::Spreadsheet.open(create_temp_file)
  # access the spreadsheet as usual
rescue
  @tmp&.unlink
end

This preserves the file prefixes and extensions (important to let Roo infer what the file is) and ensures the file get deleted when done.

1
Madrid On

ModelName.filename.blob.open do |file|
write your code here ...
end

0
Mateus C On

You can temporarily download the file with open method

report.search_report.open do |file|
    xlsx = Roo::Spreadsheet.open(file)
end