rails - x-sendfile + temporary files

admin

Administrator
Staff member
Some time ago I wrote <a href="https://stackoverflow.com/questions...-temp-files-in-a-portable-way/2146814#2146814">a question</a> regarding the use of temporary files within a rails app. On thar particular case, I decided to use <a href="http://www.ruby-doc.org/stdlib/libdoc/tempfile/rdoc/index.html" rel="nofollow noreferrer">tempfile</a>

This causes a problem if I also want to use the
Code:
x-sendfile
directive (<a href="http://vijaydev.wordpress.com/2010/12/15/rails-3-and-apache-x-sendfile/" rel="nofollow noreferrer">as a parameter in Rails 2, or as a configuration option in Rails 3</a>) so that the file sending is handled by my web server directly, not my rails app.

So I thought about doing something like this:

Code:
require 'tempfile'

def foo()
  # creates a temporary file in tmp/
  Tempfile.open('prefix', "#{Rails.root}/tmp") do |f|
    f.print('a temp message')
    f.flush
    send_file(f.path, :x_sendfile =&gt; true) # send_file f.path in rails 3
  end
end

This setup has one issue: the file is deleted before being sent!

On one hand,
Code:
tempfile
will delete the file as soon as the
Code:
Tempfile.open
block is over. On the other,
Code:
x-sendfile
makes the send_file call asynchronous - it returns very quickly, so the server hardly has time to send the file.

My best possible solution right now involves using non-temporary files (File instead of Tempfile), and then a cron task that erases the temp folder periodically. This is a bit inelegant since:

<ul>
<li>I have to use my own tempfile naming scheme</li>
<li>Files stay on the tmp folder longer than they are needed.</li>
</ul>

Is there a better setup? Or, is there at least a "success" callback on the asynchronous
Code:
send_file
, so I can erase f when it's done?

Thanks a lot.