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 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

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)