LoginSignup
5
5

More than 3 years have passed since last update.

【Rails】rakeタスクを実装する

Last updated at Posted at 2020-09-09

rakeタスクとは

ファイルに記述した処理をコマンドラインから実行する機能です。
ユーザーの属性に応じてステータスを変更する、CSVデータをインポートする、任意のタイミングでユーザーにメールを送る、などなど様々な用途で使われます。

基本的な使い方

タスクファイルを生成

$ rails g task qiita_task

実行したい処理を記述

namespace :qiita_task do
  desc 'hello worldします'
  task :hw do
    puts 'Hello World'
  end
end

実行

$ rake qiita_task:hw

その他

タスクの中にDBに接続する処理が含まれる場合

DBに接続する場合、以下のようにenvironmentと記述する

namespace :qiita_task do
  desc '最近登録したユーザーにメールを送信'
  task send_email_to_recent_users: :environment do
    recent_users = User.where('updated_at <= ?', Time.zone.parse('2020/09/08 15:50:00'))
    recent_users.each do |ru|
      ru.send_email
    end
  end   
end

本番環境で実行する

プロジェクトのルートディレクトリ(Gemfileとかがあるとこ)で、RAILS_ENV=productionをつけて実行。

$ rake qiita_task:hw RAILS_ENV=production

タスク一覧を表示

デフォルトで定義されているタスクと、自分が作成したタスクがずらっと表示されます。

$ rake -T

参考

5
5
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
5
5