Remove Files After a Destroy

Posted by Chad

This blog was started with the purpose of writing mostly about code. I have yet to do so until now. Here we go.

My current project, similar to AmieStreet, requires the uploading of files (eg mp3’s) that are linked to a record in the database. While the database stores all of the information about the song (eg Title) the mp3 itself is stored on the filesystem. If, for whatever reason, we delete the record from the database we should also remove the associated mp3 from the filesystem.

Rails makes this incredibly easy for us. As the convention goes, I will call the delete a destroy from here on out.

Version 1
def after_destroy
  if FileTest.exist?(source)
    FileUtils.rm self.source
  end
  if FileTest.exist?(clip)
    FileUtils.rm clip
  end
end

This was my original code. I have 2 mp3 files, the source (entire song) and the clip (sample from song), each file should be removed from the filesystem after the record is destroyed. Conveniently, the after_destroy callback lets me run my logic after the destroy.

Since I have 2 files, I test to see if each exists if so I remove it. Note: the source and clip methods just return full paths to the files, like RAILS_ROOT+"/path/to/file.mp3".

It could be so much better, let’s DRY things up a bit.

Version 2
def after_destroy
  removables [source, clip]
end
def removables(paths = [])
  paths.each{|p| FileUtils.rm p if FileTest.exist?p }
end

Here I wanted to make a method that I could feed multiple file paths and it would execute the logic. So I made the removables method, which steps through each path in the paths array and removes the file if it exists. This is pretty clean, but it gets better.

Version 3, Final
def after_destroy
  FileUtils.rm_f [source, clip]
end

Upon closer inspection, I noticed that the FileUtils.rm* methods actually accept a list of files to delete. And, with the force option the method does not throw errors if the file is not there. I was so used to always having to check whether a file existed, in order to avoid errors that come up if I tried to delete a nonexistent file, that I did not even think this could be done. Of course, with Ruby, the solution is simple.

Conclusion

This is a perfect example of how I am trying to think like a Rubyist. From V1 to V3, Final took me about 5 minutes so I feel that I am getting a good deal better … and oh so addicted.