Skip to content

Instantly share code, notes, and snippets.

@rafaelp
Last active April 18, 2024 11:27
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save rafaelp/4467738 to your computer and use it in GitHub Desktop.
Save rafaelp/4467738 to your computer and use it in GitHub Desktop.
Rake task to find unused images on Rails project to deletion.
# It requires ACK - http://betterthangrep.com/
task :find_unused_images do
images = Dir.glob('app/assets/images/**/*')
images_to_delete = []
images.each do |image|
unless File.directory?(image)
# print "\nChecking #{image}..."
print "."
result = `ack -1 -G '(app|public)' --ruby --html --css --js #{File.basename(image)}`
if result.empty?
images_to_delete << image
else
end
end
end
puts "\n\nDelete unused files running the command below:"
puts "rm #{images_to_delete.join(" ")}"
end
@aneziocampos
Copy link

It doesn't work with ack 2, I've rollback to version 1.96 and it worked

@bschaeffer
Copy link

To upgrade to ack 2:

ack -g -i '(app|public)' | ack -x -w #{File.basename(image)}

@danielricecodes
Copy link

Add single quotes (e.g. ') to account for file names containing special characters such as &.

-> ack -g -i '(app|public)' | ack -x -w '#{File.basename(image)}'

@MichaelAPL
Copy link

Thank you! very helpful!

@JoeWoodward
Copy link

This doesn't account for images that are used in an interpolated context

def slider_image(brand)
  image_tag("#{brand}_logo_large.png")
end

@diego-aslz
Copy link

Here's a clean version using the updated ack command from @danielricecodes:

task :find_unused_images do
  images_to_delete = Dir.glob('app/assets/images/**/*').reject(&File.method(:directory?)).select do |img|
    print '.'
    `ack -g -i '(app|public)' | ack -x -w #{File.basename(img).shellescape}`.empty?
  end

  puts "\n\nDelete unused files running the command below:"
  puts "rm #{images_to_delete.map(&:shellescape).join(' ')}"
end

@mauu-alpha
Copy link

shellescape

Add the -1 option to continue with the next file if a result was found
ack -g -i '(app|public)' | ack -x -1 -w #{File.basename(img).shellescape}.empty?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment