Read more

Carrierwave: How to remove container directories when deleting a record

Arne Hartherz
April 26, 2021Software engineer at makandra GmbH

When deleting a record in your Rails app, Carrierwave automatically takes care of removing all associated files.
However, the file's container directory will not be removed automatically. If you delete records regularly, this may be an annoyance.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Here is a solution which was adapted from the Carrierwave GitHub wiki Show archive.org snapshot and cleans up any empty parent directories it can find.

class ExampleUploader < CarrierWave::Uploader::Base

  storage :file
  after :remove, :remove_empty_container_directory
  
  def store_dir
    # You implemented this in your uploaders already.
  end

  def remove_empty_container_directory(dir = store_dir)
    return unless Dir.empty?(dir)

    Dir.delete(dir)
    remove_empty_container_directory(File.dirname(dir))
  end

end

I suggest you also structure your file system for performance.

Posted by Arne Hartherz to makandra dev (2021-04-26 09:19)