Rails how to delete a file without failing on error

I'm using JPEGCAM to allow users to take a profile pic with their web cam. This uploads a temporary file as so:

def ajax_photo_upload    
  File.open(upload_path, 'w:ASCII-8BIT') do |f|
    f.write request.raw_post
  end
  # @user.photo = File.open(upload_path)
  @user.assign_attributes(
    :photo => File.open(upload_path),
    :orig_filename => "#{current_user.full_name}.jpg"
  )
  if @user.save
  respond_to do |format|
  .....
private

  def upload_path # is used in upload and create
    file_name = session[:session_id].to_s + '.jpg'
    File.join(::Rails.root.to_s, 'public', 'temp', file_name)
  end

What's the best way to go about deleting this temporary file safely? Thanks


Solution 1:

When you know that you are done with the file:

File.delete(path_to_file) if File.exist?(path_to_file)

Another thing: make sure that you always close files that you have opened, an operating system can only handle a certain number of open files/file descriptors and you'll may run into strange bugs when you pass that limit... So when you want to open files in Ruby always either use the block form:

File.open(path) do |f|
  # ...
end

and Ruby will close the file automatically for you. If the block form is not usable, you have to close files by yourself:

f = File.open(path)
# ...
f.close

So make sure to close the file that you pass to @user.assign_attributes(...)...

Solution 2:

If you are sure you are done with it, why not just use FileUtils.rm or FileUtils.rm_f?

FileUtils.rm_f(upload_path)

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-rm_f

You could also ignore this in Rails, and have a cron that wakes up and deletes files older than a day from the temp directory that match these temp files. That has the benefit of some margin for error if a file fails to be reprocessed - you don't rm it immediately - and the file operation is not done on the request/response loop for Rails, which will then respond a bit faster.