DEV Community

@kon_yu
@kon_yu

Posted on • Updated on

Rake to flush out and delete unused image files in Rails

Introduction.

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.

Prerequisites.

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
Enter fullscreen mode Exit fullscreen mode

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
      end
    end
  end
  puts "Delete unused files running the command below:"

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

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

Enter fullscreen mode Exit fullscreen mode

Usage

> bin/rake find_unused_images
Enter fullscreen mode Exit fullscreen mode

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:
app/assets/images/xxx1.png
app/assets/images/xxx/xxx2.png
..
.
# The rm command to delete unused files in one shot
rm app/assets/images/xxx1.png app/assets/images/xxx/xxx2.png
Enter fullscreen mode Exit fullscreen mode

Top comments (0)