LoginSignup
5
3

More than 5 years have passed since last update.

Rails RunnnerでControllerの機能を使ったバッチ処理を書きたい

Posted at

概要

Rails Runnnerを使ってバッチ処理を作成したい。
バッチ処理はModelの操作が主だが、一部Controllerに実装されている機能を使用したい。

  • Ruby 2.3.4
  • Rails 5.0.3

結論

処理はControllerに実装してしまって、バッチからはControllerだけを呼び出すだけにする。

実装

./lib配下が本番環境ではautoloadされない件への対応。

./config/application.rb
# 下記の一文を追加
config.paths.add 'lib', eager_load: true

Controllerに処理を実装。

./controllers/test_controller.rb
class TestController < ApplicationController
  def batch
    # runnnerで起動したい処置をこのあたりにゴニョゴニョ
  end
end

呼び出し。

./lib/tasks/test_batch.rb
class TestBatch
  def self.execute
    controller = TestController.new
    controller.batch
  end
end
TestBatch.execute

bundle exec bin/rails runner lib/tasks/test_batch.rb
上記コマンドで実行。controllerの処理が呼び出されるので、あとはいつもどおりに実装すればOK。

とりあえず動いたのでよいものとします。
Rubyは触りたてなこともあり、実は他にやりようがあったのでは感が否めないところないでもありません。

参考

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