LoginSignup
18
17

More than 5 years have passed since last update.

rails runner を使った batch を書くときの工夫

Posted at

概要

Web アプリケーションは普通に動かしつつ,裏で batch 処理をがんがん動かすアプリケーションを rails で書いた。こういうアプリケーションでは以下のようなことを各 batch が備えていると非常に捗る。

  • dryrun モード
  • log は batch ごとに別なファイルに吐かせる

具体的には以下。

# dryrun
# log はファイルでなく標準出力に。debug log も吐く。
$ bundle exec rails runner 'BatchExample.dryrun'

# exec
# log はこのバッチ専用のファイル (=log/batch/batch_example.log) に。debug log は吐かない。
$ bundle exec rails runner 'BatchExample.exec'

これをどのように実現したかを備忘録的に残しておく。

実現方法

まず batch の基底クラスを作る。

lib/batch/base.rb
require 'logger'

class Batch::Base
  @@is_dryrun = false

  class << self
    def logger
      @@logger ||= Logger.new(
        dryrun? ? STDOUT : File.join(Rails.root, 'log', "#{self.to_s.underscore}.log")
      )
    end

    def dryrun(*args)
      @@is_dryrun = true
      logger.level = Logger::DEBUG
      exec(*args)
    end

    def dryrun?
      @@is_dryrun
    end
  end
end

あとはこの基底クラスを継承させて batch を書く。

lib/batch/batch_example.rb
class Batch::BatchExample < Batch::Base
  def self.exec
    logger.info('start.')
    logger.debug('show only in dryrun mode.')
    unless dryrun?
      # some processes
    end
    logger.info('finish.')
  end
end

これだけ。
log は log/batch/batch_exmaple.log に吐かれる。

補足事項

log 用のディレクトリ (log/batch) は以下のようにして git keep する (.gitignore の書き方が回りくどい...)。

.gitingore
/log/*
!/log/.keep
!/log/batch/
/log/batch/*
!/log/batch/.keep
18
17
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
18
17