Skip to content

How to: Delete cache garbage directories

malclocke edited this page Mar 11, 2013 · 8 revisions

The tmp cache directory can fill up with empty dirs if it's not cleaned up. See issue #338 and #393.

To fix this add some callbacks in your uploader like in the following example

class FileUploader < CarrierWave::Uploader::Base
  storage :file
  
  before :store, :remember_cache_id
  after :store, :delete_tmp_dir

  # store! nil's the cache_id after it finishes so we need to remember it for deletion
  def remember_cache_id(new_file)
    @cache_id_was = cache_id
  end
  
  def delete_tmp_dir(new_file)
    # make sure we don't delete other things accidentally by checking the name pattern
    if @cache_id_was.present? && @cache_id_was =~ /\A[\d]{8}\-[\d]{4}\-[\d]+\-[\d]{4}\z/
      FileUtils.rm_rf(File.join(root, cache_dir, @cache_id_was))
    end
  end
end

You can also periodically clean old cache dirs ( < 1 day ) by calling CarrierWave.clean_cached_files! daily by means of a rake task or a "rails runner".

Carrierwave does not clean these dirs for you because they can vary according to your configuration.

Special Considerations

This method breaks uploaders that have more than one version defined. Your first version will be saved, but afterwards the cleanup code will run and remove the tmp file that is used to generate additional versions. In that case, you are better off creating a rake task that cleans out the tmp folders periodically.

Garbage rack upload files in tmp dir

If your /tmp dir gets full of rack tmp upload garbage, you can delete these in a callback like so:

class FileUploader < CarrierWave::Uploader::Base
  after :store, :delete_old_tmp_file

  # remember the tmp file
  def cache!(new_file)
    super
    @old_tmp_file = new_file
  end
  
  def delete_old_tmp_file(dummy)
    @old_tmp_file.try :delete
  end
end
Clone this wiki locally