attachment_fu: how to delete the original file

In one of our ongoing rails projects, we need to delete the original file after the user uploads an image file.

We use attachment_fu to handle file uploading. My first try was to delete the file in the after_create block of the Photo class, but it seemed at that time the file hasn’t been copied to the directory yet.

Fortunately attachment_fu provides an after_attachment_saved callback which will be called after an attachment has been saved to the file system. That’s exact what we need to get our job done:

class Photo < ActiveRecord::Base
  has_attachment options_for_attachment_fu

  after_attachment_saved do |foto|
    # delete original file for disk space saving
    FileUtils.rm foto.full_filename if foto.parent.nil?
  end

end

Very handy. Be aware though now calling the public_filename without a :thumbnail parameter on a Photo instance would return an image url that doesn’t exist.

See also: Use S3 Virtual Hosting Name With attachment_fu