Is it possible to disable deletion of a cached file using the carrierwave uploader?

119 Views Asked by At

I have a CarrierWave uploader, I need to disable the deletion of cached files after saving them to the store. To then perform some kind of operation with this cached file and delete it manually.

My uploader:

class FileUploader < CarrierWave::Uploader::Base
  def store_dir
    "store"
  end

  def cache_dir
    'tmp'
  end

  def size_range
    0..100.megabytes
  end
end
4

There are 4 best solutions below

0
Milind On

You can use the callbacks, before/after store.

Sharing a snippet here along with a link -

after :store, :do_something_and_delete_manually

This callback is triggered after file is uploaded. Make sure you delete the cache manually after using the callback.Just play around to understand how it works.

Check this Carrierwave WIKI page for more details.

0
raj_acharya On

You can override the remove_cached_versions! method

The below code will disable the deletion of all cached versions of an uploaded file

class FileUploader < CarrierWave::Uploader::Base

  def remove_cached_versions!
    # perform the intended operation here
  end

end

You can disable the deletion of cached files after saving them to the store. By setting the keep_cached_files option in your uploader configuration

# config/initializers/carrierwave.rb

CarrierWave.configure do |config|
  config.keep_cached_files = true
end
3
leonchik12 On

I found what I think is the most suitable option for me. I dug into the guts of the gem and noticed that the cache is deleted if method delete_tmp_file_after_storage returns true. So I just overridden the method and that's it.

  def delete_tmp_file_after_storage(config = nil)
    @delete_tmp_file_after_storage ||= config.present?
  end

I made cache deletion disabled by default, but with the ability to enable it if necessary.

0
Julien Chien On

As @leonchik12 pointed out, this behavior is controlled by the @delete_tmp_file_after_storage instance variable (code seems to be here). Though their answer could work, the better way to override this configuration is via a standard configuration block you should have somewhere in your project.

Read the gem's README, and you can see it has a configuration section here. Unfortunately the docs are not clear what config options there are, but looking at the code you can see all possible configurable options in configuration.rb

Looking at the options, you will notice there is a configuration for delete_tmp_file_after_storage on line 22.

So putting all this info together, you can simply do something like the following:

CarrierWave.configure do |config|
  config.delete_tmp_file_after_storage = false
  # you can add more configs below
end

You can reference this article's example, which uses .configure. More examples can be found via the gem's wiki