nozayasu-memo

プログラムのメモ

Batchとかの実行履歴を残す処理を、yield 使って修正した時のメモ

元々のコード

module Batch
  class Sample
    def execute
      background_job_history = BackgroundJobHistory.start
      begin
        # 実処理
        background_job_history.finish(error: false)
      rescue => e
        background_job_history.finish(error: true)
      end
    end
  end
end

こういう感じのコード(あくまでこういう感じ)でBatchの実行履歴みたいなのを記録していく処理があった。 BackgroundJobHistoryという記録用のModelは、BatchとWorkerとか複数から呼び出される

思ったこと

  • ちょっと毎回エラーハンドリングと記録する処理やるの漏れありそうだな
  • 最初はBatchのBaseClassにまるっともっていこうかな?と思ったけどWorkerもあるなぁ、BackgroundJobHistory側に状況に合わせて記録するって部分任せよう
  • 同僚がtransactionみたいにblockでよしなに処理されるといいなって言っていた

修正したコード

module Batch
  class Sample
    def execute
      BackgroundJobHistory.recording do
        # 実処理
      end
    end
  end
end

Class BackgroundJobHistory
  class << self
    def recording
      background_job_history = create
      begin
        yield
      rescue => e
        background_job_history.error
        raise e
      end
      background_job_history.done
    end
  end
end

履歴を記録するよってのと、どの処理の?っていうのをyieldつかって表現したよってメモでした