LoginSignup
31
32

More than 5 years have passed since last update.

Rubyのoptparseを軽く使いたい時に悩む

Last updated at Posted at 2013-05-20

コマンドライン引数を受け取るスクリプトを書いている時に使うと、とても便利なoptparse。

library optparse

OptionParser 自体は、どのオプションが指定されたかを記憶しません。 後の処理の方で、オプションによる条件判断を加えるには、 他のコンテナに格納します。

なので、公式にあるサンプルは下記。

require 'optparse'
opt = OptionParser.new

OPTS = {}

opt.on('-a') {|v| OPTS[:a] = v }
opt.on('-b') {|v| OPTS[:b] = v }

opt.parse!(ARGV)
p ARGV
p OPTS

ruby sample.rb -a foo bar -b baz
# => ["foo", "bar", "baz"]
    {:a=>true, :b=>true}

そうなんだけど、何かシックリと来ない。(僕の感覚が訓練されてないだけの可能性もある。)
OptionParserを拡張か継承でもして、持たせるようにするとopt.config[:hoge]とか出来るけど、parserではなくなるよなぁ・・・とそれなりに悩むのです。

なので、最近は下記のように使っています。

if __FILE__ == $0
  module Viewer
    def view_option
      puts option.inspect
    end
  end

  module Option
    def option
      @option ||= {}
    end
  end

  class Execute < BasicObject
    extend ::Viewer
    extend ::Option
  end

  require "optparse"
  OptionParser.new{|option|
    option.version = "0.0.1"
    option.on("-i file", "--input", "input file."){|fileName| Execute.option[:inputFileName] = fileName}
    option.on("-o [file]", "--output", "output file."){|fileName| Execute.option[:outputFileName] = fileName}
  }.parse!

  Execute::view_option
end

余計、不格好だし、手軽じゃなくなった!(°ω°
どなたかセンスをくださいorz

コメントで教わったtrollopで書いてみた

udzuraさん。ありがとうございます(^q^

インストール

$gem install trollop

こんな感じで書いた

if __FILE__ == $0
  module Viewer
    def view_option
      puts option.inspect
    end
  end

  module Option
    attr_accessor :option
  end

  class Execute < BasicObject
    extend ::Viewer
    extend ::Option
  end

  require "trollop"
  Execute.option = Trollop::options do
    version "0.0.1"
    opt "input", "input file."#, short: "-i"
    opt "output", "output file.", default: "#{Time.now.strftime("%Y%m%d_%H%M%S")}.out"
  end

  Execute.view_option
  p ARGV
end
  • オプションを指定する時に、shortを指定すると短縮オプションを作れる
    • 指定しなくても勝手に作ってくれる
    • 上記例だと、--inputの場合は、-i
  • defaultも作れる
    • --helpをした時に表示してくれる

実行結果

$ ruby trollop.rb --help
0.0.1
Options:
       --input, -i:   input file.
  --output, -o <s>:   output file. (Default: 20130520_221406.out)
     --version, -v:   Print version and exit
        --help, -h:   Show this message

$ ruby trollop.rb -i "input.log"
{"input"=>true, "output"=>"20130520_221415.out", :version=>false, :help=>false, :input_given=>true}
["input.log"]

$ ruby trollop.rb -i "input.log" "hoooooooo" -o "output.log"
{"input"=>true, "output"=>"output.log", :version=>false, :help=>false, :input_given=>true, :output_given=>true}
["input.log", "hoooooooo"]

まだ解説を読んでいる途中ですが、良い感じですね。

31
32
5

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
31
32