LoginSignup
5
5

More than 5 years have passed since last update.

rails runner script.rb --help で rails runner に help を喰われない方法、もしくは rails runner を省略して script.rb を実行する方法

Last updated at Posted at 2016-01-20

やりたいこと: rails runner script.rb で rails のコンテキストでスクリプトを実行することができるが、rails runner script.rb --help とすると、script.rb の help ではなく、rails runner の help が出てしまう。なんとかしたい。

bin/rails と https://github.com/rails/rails/blob/f8234313feab83c65912b2d96a6dd8e0149b8642/railties/lib/rails/commands/runner.rb を参考に以下のようになった。

lib/rails_runner.rb を用意

APP_PATH = File.expand_path('../../config/application', __FILE__) unless defined?(APP_PATH)
require_relative '../config/boot'

options = { environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup }
ENV["RAILS_ENV"] = options[:environment]

require APP_PATH
Rails.application.require_environment!
Rails.application.load_runner

script/foo.rb から lib/rails_runner.rb を require (もしくは load)

#!/usr/bin/env ruby
require_relative '../lib/rails_runner'
require 'optparse'

opt = OptionParser.new

opt.on('-a VAL') {|v| p v }
opt.on('-b') {|v| p v }

opt.parse!(ARGV)

これで script/foo.rb --help のように実行できるようになった。

$ chmod a+x script/foo.rb
$ script/foo.rb -h
Usage: foo [options]
    -a VAL
    -b
5
5
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
5