如何通过send_file发送文件后删除Sinatra中的文件?

Joh*_*lly 12 ruby sinatra

我有一个简单的sinatra应用程序需要生成一个文件(通过外部进程),将该文件发送到浏览器,最后从文件系统中删除该文件.这些方面的东西:

class MyApp < Sinatra::Base
  get '/generate-file' do

    # calls out to an external process, 
    # and returns the path to the generated file
    file_path = generate_the_file()  

    # send the file to the browser
    send_file(file_path)

    # remove the generated file, so we don't
    # completely fill up the filesystem.
    File.delete(file_path)

    # File.delete is never called.

  end
end
Run Code Online (Sandbox Code Playgroud)

但是,似乎send_file调用完成了请求,并且它之后的任何代码都没有运行.

有没有办法确保生成的文件在成功发送到浏览器后被清除?或者我是否需要在某个时间间隔内使用运行清理脚本的cron作业?

fl0*_*00r 3

不幸的是,当您使用 send_file 时没有任何回调。这里常见的解决方案是使用 cron 任务来清理临时文件