Deleting stale Paperclip attachment styles from the server

Posted . Visible to the public.

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.

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


Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2017-07-27 14:46)