😀

Rakeタスクの実行に前処理を追加する

に公開

やりたいこと

本番環境などで一部のRakeタスクを慎重に実行したい。
例えば db:dropRUN=true をつけたときのみ実行するようにし、それ以外のときは中断させたい。

解: .enhance で前処理を追加する

.enhance で指定したRakeタスクの前処理を追加できる。

Rake::Task[タスク名].enhance(前処理)

以下の例では RAILS_ENV=production の際に RUN=true がついてない場合は、 db:drop を中断するRakeタスク。

Rakefile
namespace :db do
  task :abort_if_no_run do
    abort 'Please set RUN environment variable.' if Rails.env.production? && ENV['RUN'] != 'true'
  end

  Rake::Task['db:drop'].enhance(['abort_if_no_run'])
end

実行すると以下のようになる。

$ ./bin/rails db:drop RAILS_ENV=production 
Please set RUN environment variable.

$ ./bin/rails db:drop RAILS_ENV=production RUN=true
Dropped database 'storage/production.sqlite3'
Dropped database 'storage/production_cache.sqlite3'
Dropped database 'storage/production_queue.sqlite3'
Dropped database 'storage/production_cable.sqlite3'

Discussion