evans
evans

Reputation: 563

How do I write data to a temporary file?

I have an original file that I need to copy to temporary.
I'm trying to do it inside the Tempfile.create block
But the file does not appear.

How correctly to create a temporary file?

dest_path_to = "public/medicine/reports/#{report_id}"
FileUtils.mkdir_p(dest_path_to)
original = File.open(pdf_path).read

file = Tempfile.create("report-#{report_id}.pdf", dest_path_to) do |f|
  f.write original
end

Upvotes: 0

Views: 97

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

From the documentation (emphasis mine):

If a block is given, then a File object will be constructed, and the block is invoked with the object as the argument. The File object will be automatically closed and the temporary file is removed after the block terminates. The call returns the value of the block.

If you want the file show up in the filesystem, for whatever reason, then don't use the block form of Tempfile.create.

Upvotes: 3

Related Questions