54
42

More than 5 years have passed since last update.

Rails runnerを使ってファイルを実行しました

Last updated at Posted at 2014-12-08

Railsにrunnerというバッチ処理などを実行できるものがあるので、runnerを実行しました。

実行用スクリプトを用意

実行用に、lib/batch/helloworld.rbというスクリプトを用意しました。

helloworld.rb
class Batch::Helloworld
  def self.helloworld
    puts "HelloWorld!"
  end
end

runnerで実行

helloworld.rbを実行します。

runnerでファイルを実行
bundle exec rails runner Batch::Helloworld.helloworld
# 出力
HelloWorld!

おまけ

lib/batch/get_api.rb というスクリプトを用意しました。

get_api.rb
class Batch::GetApi
  def self.get_api
    # API を取得する処理
    puts "GET API"
  end
end
runnerでファイルを実行
bundle exec rails runner Batch::GetApi.get_api
# 出力
GET API

runnerの実行でエラーが出る場合

runnerを実行した際にエラーが発生することがありました。

エラーが発生
/home/vagrant/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/commands/runner.rb:62:in `<top (required)>': uninitialized constant Batch (NameError)

これは/lib以下が読み込めていないことが原因のようです。
config/application.rbに読み込み設定を記述します。

application.rbにautoload_pathsを追加
class Application < Rails::Application
  
  config.autoload_paths += Dir["#{config.root}/lib"]
  
end

このように書くことでエラーは発生せず、runnerを実行することができました。

おまけ Herokuでrunnerを実行

Herokuでrunnerコマンドを実行する場合は、heroku runをつければ動くみたいです。

herokuでrunnerを実行
heroku run rails runner Batch::GetApi.get_api --app pugiemonn
54
42
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
54
42