LoginSignup
25
23

More than 5 years have passed since last update.

rails runnerで起動するスクリプトにオプションを渡す

Posted at

基本的にはそのまま末尾に列挙する、で問題ありません。

require 'optparse'

options = {}

OptionParser.new { |o|
  o.banner = "Usage: #{$0} [options]"
  o.on("--opt1=OPT", "option1") { |v| options[:opt1] = v }
  o.on("--opt2=OPT", "option2") { |v| options[:opt2] = v }
}.parse!(ARGV.dup)

p options
$ bundle exec rails runner script/do_something.rb --opt1=foo --opt2=bar
{:opt1=>"foo", :opt2=>"bar"}

が、--helpは rails runnerのオプションとして定義されているので、そのまま渡してしまうと先に喰われて起動し、scriptに渡されない問題があります。

$ bundle exec rails runner script/do_something.rb --help
Usage: runner [options] ('Some.ruby(code)' or a filename)

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

    -h, --help                       Show this help message.

You can also use runner as a shebang line for your scripts like this:
-------------------------------------------------------------
#!/usr/bin/env /Users/yoshida/proj/miil/foodflowrb/script/rails runner

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

そのため、--で標準入力を実際実行したいスクリプトに渡すようにします。普段から使うようにしておくと、変なハマり方もしなくて済みそうです。
ただ、ARGV--が含まれるので取り除く必要があります。

require 'optparse'

options = {}
argv = ARGV.dup
if argv.include? "--"
  argv.delete "--"
end

OptionParser.new { |o|
  o.banner = "Usage: #{$0} [options]"
  o.on("--opt1=OPT", "option1") { |v| options[:opt1] = v }
  o.on("--opt2=OPT", "option2") { |v| options[:opt2] = v }
}.parse!(argv)

p options
$ bundle exec rails runner script/do_something.rb -- --help
Usage: script/do_something.rb [options]
        --opt1=OPT                   option1
        --opt2=OPT                   option2
25
23
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
25
23