1

以下代码旨在汇总一些 PDF 文档并发送包含所有 PDF 的 zip 文件。该代码有效,但只有 50% 的时间。

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

另外 50% 的时间它会抛出以下错误 -

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

这里的任何建议/指导将不胜感激!第一次使用 Tempfile 和 Rubyzip。

4

1 回答 1

0

zipfile这可能是因为在块结束时 zip gem 实际引用之前,内部 Tempfile 被垃圾收集并从磁盘中删除(有时) 。我只是将它们推入一个数组以绕过它:```

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

```

于 2017-03-06T20:22:05.520 回答