How can I delete a file in Sinatra after it has been sent via send_file?

send_file is streaming the file, it is not a synchronous call, so you may not be able to catch the end of it to the cleanup the file. I suggest using it for static files or really big files. For the big files, you'll need a cron job or some other solution to cleanup later. You can't do it in the same method because send_file will not terminate while the execution is still in the get method. If you don't really care about the streaming part, you may use the synchronous option.

begin
   file_path = generate_the_file()  
   result File.read(file_path)
   #...
   result # This is the return
ensure
   File.delete(file_path) # This will be called..
end

Of course, if you're not doing anything fancy with the file, you may stick with Jochem's answer which eliminate begin-ensure-end altogether.


Unfortunately there is no any callbacks when you use send_file. Common solution here is to use cron tasks to clean temp files


It could be a solution to temporarily store the contents of the file in a variable, like:

contents = file.read

After this, delete the file:

File.delete(file_path)

Finally, return the contents:

contents

This has the same effect as your send_file().

Tags:

Ruby

Sinatra