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

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)