Rake to flush out and delete unused image files in Rails

konyu profile image @kon_yu Updated on ・2 min read


If you run a web service for a few years, before you know it, you'll have an image file that you don't use at all.
It's hard to check if you're not using each one of them, so I'll use the Rake task to flush out all the unused image files and delete them.

Rake tasks are performed and committed in a local environment.

In this case, I use the silver searcher as a file search command.
The silver searcher checks the .gitignore file, for We don't want the files to be searched for.
You can exclude the gem from the search, which makes the process faster, for example, if you install the gem under /vendor/bundler.


For Git-managed Rails projects
You must have the silver searcher installed on your computer.

Install the silver searcher on homebrew

If you don't have the silver searcher installed, you can easily install it with homebrew.

brew install ag

Rake files to flush out and delete unused image files in Rails

Rake file body

# It requires AG - https://github.com/ggreer/the_silver_searcher
task :find_unused_images do
  images = Dir.glob("app/assets/images/**/*")

  images_to_delete = []
  images.each do |image|
    unless File.directory?(image)
      puts "Checking #{image}"
      # Use -G to specify the extension to check. You can use --ruby, --sass options.
      result = `ag -G "slim|erb|js|css|sass|scss|rb" #{File.basename(image)} .`

      if result.empty?
        images_to_delete << image
  puts "Delete unused files running the command below:"

  puts images_to_delete.join(" \n").to_s

  puts "-----------------------------------"
  puts "rm #{images_to_delete.join(" ")}"


> bin/rake find_unused_images

Execution result

# Searching for a file
Checking app/assets/images/xxx1.png
Checking app/assets/images/xxx/xxx2.png
# List of unused files
Delete unused files running the command below:
# The rm command to delete unused files in one shot
rm app/assets/images/xxx1.png app/assets/images/xxx/xxx2.png


Editor guide