LoginSignup
17
16

More than 5 years have passed since last update.

Railsで未使用の画像ファイルを洗い出して削除するRake

Last updated at Posted at 2016-03-04

はじめに

Webサービスを数年運用すると、いつの間にか全く使っていない画像ファイルが出てくる
一つ一つ本当に使っていないか調べるのは骨が折れるのでRakeタスクでまとめて使ってない画像ファイルをあぶり出して削除する

Rakeタスクはローカル環境で実施し、コミットする

今回はファイル検索のコマンドにthe silver searcherを利用している。
the silver searcherは.gitignoreをチェックして無視される対象のファイルは検索対象にしないので
gemを /vender/bundler以下にインストールしている場合など検索対象から外せて高速に処理できる

前提条件

Gitで管理されたRailsプロジェクトが対象
the silver searcherがインストールされていること

homebrewでthe silver searcherをインストール

the silver searcherがインストールされていない場合、homebrewで簡単にインストールできる

brew install ag

Railsで未使用の画像ファイルを洗い出して削除するRakeファイル

Rakeファイル本体

# 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}"
      # -G でチェックする拡張子を指定 --rubyや--sassでも検索できる
      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

使い方

> bin/rake find_unused_images

実行結果

# 検索中のファイル
Checking app/assets/images/xxx1.png
Checking app/assets/images/xxx/xxx2.png
..
.
# 使われていないファイル一覧
Delete unused files running the command below:
app/assets/images/xxx1.png
app/assets/images/xxx/xxx2.png
..
.
# 使われていないファイルを一発で削除するrmコマンド
rm app/assets/images/xxx1.png app/assets/images/xxx/xxx2.png

ref: ackコマンドで実施する方法(これをthe silver searcherに適用した) - https://gist.github.com/stereodenis/10846043

17
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
16