Say that I open a file in Ruby like this:
f = File.open('diagram.txt', 'r')
Right now, in order to close and delete that file I have this code:
begin
f = File.open('diagram.txt', 'r')
ensure
if !f.nil? && File.exist?(f)
f.close unless f.closed?
File.delete(f)
end
end
I found this code to be too complicated, and the File.exist?(f)
would fail if the f is closed already. So, what is the correct approach to avoid the closing and deleting of the file raising exceptions?
Note: I know that passing a block to File.open will close the file directly, however, I am looking for the general approach of closing and deleting.
Since your diagram.txt file is not guaranteed to exist in your example code, your bigger problem is handling the Errno::ENOENT exception. You can Call File#open in a self-closing block, and then use rescue to handle the exception if you try to open or delete a missing file. For example:
begin
File.open('diagram.txt', 'r') do |f|
# do something with file
File.delete(f)
end
rescue Errno::ENOENT
end