158
137

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rails runnerを使ってみた

Posted at

rails runnerとは

railsの環境を読み込んだ上で任意のrubyコードが実行できるようです。
batch処理とかの時に使えるんじゃないでしょうか。
helpを見ると以下のように使うらしい。環境も指定できて便利ですね。

% rails runner -h
Usage: rails runner [options] [<'Some.ruby(code)'> | <filename.rb>]

    -e, --environment=name           Specifies the environment for the runner to operate under (test/development/production).
                                     Default: development

    -h, --help                       Show this help message.

Examples:
    rails runner 'puts Rails.env'
        This runs the code `puts Rails.env` after loading the app

    rails runner path/to/filename.rb
        This runs the Ruby file located at `path/to/filename.rb` after loading the app

You can also use runner as a shebang line for your executables:
    -------------------------------------------------------------
    #!/usr/bin/env /Users/a_kubota/bitbucket/grank/rails_runner -h runner

    Product.all.each { |p| p.price *= 2 ; p.save! }
    -------------------------------------------------------------

rubyのコードを直接実行する方法と

rails runner 'puts Rails.env'

スクリプトファイルを指定する方法があるみたい。

rails runner path/to/filename.rb

また、shebangも書けるようです。

使ってみた。

実行するファイルを作ります。batchディレクトリを作ってその中においてみました。

myapp
├── app
├── batch
│   └── hello_batch.rb
:
hello_batch.rb
class HelloBatch
  def self.execute
    puts 'hello world'
  end
end

HelloBatch.execute

実行結果

% rails runner batch/hello_batch.rb
hello world

できた!!

調べたところlibの下にclassを作ってそこを呼ぶのが作法のようでしたが、どこでも好きなところでいいんじゃないでしょうか。個人的にはlibだとちょっと違う気がしました。ここは個人差ありますよね。

参考

http://masa2sei.github.io/blog/2013/02/01/rails-rails-runner/
http://d.hatena.ne.jp/hrendoh/20111111/1320990987

158
137
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
158
137

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?