気ままに気ままのエンジニアブログ

定期的に得た知見を気ままに発信中

【Rails】バッチファイル(rake task)作成手順について

こんにちは。

家の作業場が外並みに寒い。。

どうもハチマキです。

はじめに

自動配信メール作成に伴い、バッチ処理を実装しました。
Railsバッチ処理を書く際によく使われる

  • rails runner
  • rake task
  • sidekiq

の中でも、今回はrake taskのビルドタスクバッチ手順について書いていこうと思います。(自分用のメモに近い内容になります)

では早速行きましょう!

本日の概要 : バッチファイル(rake task)作成手順について

TODO

  • taskの追加
  1. config/schedule.rbにバッチ処理を記述する
  2. lib/tasks/hoge_mail.rakeのファイルを作成し、送信処理を定義する
  3. lib/hoge_reminder/batch.rbファイルを作成し、送信条件を定義する
  • mailerの追加
  1. app/mailers/hoge_mailer.rbのmailer追加
  2. app/views/hoge_mailer/remind.html / text.hamlの追加
  • ymlファイルに追加
    • config/locales/ja.ymlに日本語名を追加
  • taskのテスト
    • ターミナルで実行しテストする

ステップ1:task追加

  • ゴール:ターミナルでbundle exec rake -Tコマンドを実行すると追加したタスクが表示される
ターミナル
$ bundle exec rake -T
....

rake hoge  # hogeの自動メール
rake piyo  # piyoの取り込み
1. config/schedule.rbにバッチ処理を記述する
#  hogeの自動メール(こちらのみ実装していきます)
every :day, at: '6:50 pm', roles: [:db] do
  rake 'yy:hoge_reminder:remind'
end if production?

# piyoの取り込み
every :day, at: '6:50 pm', roles: [:db] do
  rake 'yy:piyo_notifier:announce'
end if production?
2. lib/tasks/hoge_mail.rakeのファイルを作成し、送信処理を定義する
require Rails.root.join('lib/hoge_reminder/batch')

#namespaceを使用します
namespace :yy do
  namespace :hoge_reminder do
    desc 'Send hoge reminder'
    task remind: :environment do
      Hoge::Batch.new.run(dry_run: ENV['DRY_RUN'])
    end
  end
end 
3. lib/hoge_reminder/batch.rbファイルを作成し、送信条件を定義する
require 'batch_base'

module HogeReminder

class Batch < BatchBase
    def _run(*)
      target.each do |order|
        Hoge.remind(変数).deliver unless dry_run?
      end
    end

    def target
      変数 = 条件
      end
    end
  end
end 

ステップ2:mailerの追加

1. app/mailers/hoge_mailer.rbのmailer追加
class HogeMailer < ActionMailer::Base
  add_template_helper(ApplicationHelper)
  add_template_helper(ImageHelper)
  add_template_helper(ContentsHelper)
  add_template_helper(MailerHelper)
  add_template_helper(SearchHelper)

  layout 'hoge_mail'

  default from: Settings::MailAddress.noreply

  def remind(変数)
    subject = "#{t('hoge_mailer.remind_email.subject')}

    mail to: @user.email, subject: subject
  end
end
 
2. app/views/hoge_mailer/remind.html/ text.hamlの追加

text.html.haml

= "#{@user.name}さま"
\
リマインドメールです
\
= @user.id
の件につきましてご連絡させて頂きます。

ステップ3:ymlファイルに追加

config/locales/ja.ymlに日本名を追加
hoge_mailer:
    remind_email:
      subject: "リマインドメール"

ステップ4:taskのテスト

ターミナルで実行しテストする
$ bundle exec rake yy:hoge_reminder::remind
....

START
..
..

これでmailが飛ぶようになり、実装完了です。