Read more

Deleting stale Paperclip attachment styles from the server

Dominik Schöler
July 27, 2017Software engineer at makandra GmbH

Sometimes you add Paperclip image styles, sometimes you remove some. In order to only keep the files you actually need, you should remove stale Paperclip styles from your server.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

This script has been used in production successfully. Use at your own risk.

# Config #######################################################################
delete_styles = [:gallery, :thumbnail, :whatever]
scope = YourModel # A scope on the class with #has_attached_file
attachment_name = :image # First argument of #has_attached_file
noop = false # Use this to dry-run

# Script #######################################################################
scope.find_in_batches(:batch_size => 100) do |records|
  records.map(&attachment_name).each do |attachment|
    paths = delete_styles.map do |style|
      raise 'Refuse to delete original' if style == :original
      attachment.path(style)
    end

    existing_paths = paths.select(&File.method(:file?))
    existing_paths.each do |path|
      parent_dir = File.dirname(path)

      puts "Deleting #{path}"
      FileUtils.rm path unless noop

      puts "Deleting empty parent directory #{parent_dir}"
      # rmdir will only ever delete an empty directory
      FileUtils.rmdir parent_dir unless noop

      puts
    end
  end
end


Posted by Dominik Schöler to makandra dev (2017-07-27 16:46)