2

The following code is meant to aggregate a handful of PDF docs and send a zip file with all the PDF's contained. The code works, but only 50% of the time.

def donor_reports
@starting_date = params['date'].to_date
@ending_date = @starting_date.to_date.end_of_month
@categories = Category.all
zipfile_name = Tempfile.new(['records', '.zip'])
Zip::File.open(zipfile_name.path, Zip::File::CREATE) do |zipfile|
  @categories.each do |category|
    temp_pdf = Tempfile.new(['record', '.pdf'])
    temp_pdf.binmode
    temp_prawn_pdf = CategoryReport.new
    temp_prawn_pdf.generate_report(category, @starting_date, @ending_date)
    temp_pdf.write temp_prawn_pdf.render
    temp_pdf.rewind
    zipfile.add("#{category.name} - Donation Report.pdf", "#{temp_pdf.path}")
  end
end
send_file zipfile_name
end

The other 50% of the time it throws the following error -

   No such file or directory @ rb_sysopen - /var/folders/jy/w7tv9n8n7tqgtgmv49qz7zqh0000gn/T/record20160114-10768-1guyoar.pdf

Any advice/guidance here would be much appreciated! First time using Tempfile and Rubyzip.

EHawk
  • 21
  • 1
  • I don't have a solution to this (yet) but I wanted to let you know I have the same issue. It's an intermittent issue much of the time. – user478798 Jun 08 '16 at 00:27

1 Answers1

1

This is probably because the inner Tempfile gets garbage-collected and deleted from disk (sometimes) before the zip gem actually references when the zipfile block ends. I just push these into an array to get around it: ```

temp_files = []
Zip::File.open(temp_file.path, Zip::File::CREATE) do |zip|
    @categories.each do |category|
        temp_pdf = Tempfile.new(['record', '.pdf'])
        #...
        temp_files << temp_pdf
    end
end

```

James
  • 11
  • 1