Search code examples
rubytemporary-files

Unlink Tempfile when the path is known in Ruby


If I have the path of a Tempfile, how can I unlink it?

I know that if I have the tempfile itself (the object), I can call to:

tmp_file.unlink.

But what if I just have the path, and I want to unlink it if it exists?


Solution

  • You'd usually use File.unlink to unlink a file by name:

    File.unlink(path_to_the_temp_file)
    

    That will raise an Errno::ENOENT exception if the file doesn't exist. You can check existence before unlinking (see File.exist? and friends) or rescue and ignore that exception. Or you could go with FileUtils.remove_file and use the second parameter to ignore the exceptions:

    require 'fileutils'
    FileUtils.remove_file(path_to_temp_file, true)