読者です 読者をやめる 読者になる 読者になる

optparseを使ってみた

ARGVとOptionsParserの仕様を以下のコードで確認してみました。ARGVはOptionParser#parse!するとオプション分はシフトするみたいですね。


$ ruby --version
ruby 1.9.2p180 (2011-02-18 revision 30909) [i686-linux]

#!/usr/bin/env ruby
require "test/unit"
class OptionParserTests < Test::Unit::TestCase
  
  def test_argc
     assert_equal "0\n", `./argc.rb `
     assert_equal "1\n", `./argc.rb -l`
     assert_equal "2\n", `./argc.rb -l -c`
  end 
  def test_options
     assert_equal "{:local=>true}\n", `./optparse.rb -l`
     assert_equal "{:local=>true}\n", `./optparse.rb --local`
     assert_equal "{:local=>true, :code=>true}\n", `./optparse.rb -lc`
     assert_equal "{:local=>true, :code=>true}\n", `./optparse.rb -l -c`
     assert_equal "{:local=>true, :code=>true}\n", `./optparse.rb --local --code`
  end
  
  def test_argc
     assert_equal "0\n", `./optparse.rb -la`
     assert_equal "0\n", `./optparse.rb -lca`
     assert_equal "0\n", `./optparse.rb -l -c -a`
     assert_equal "1\n", `./optparse.rb --local --code -a ARG0` 
     assert_equal "3\n", `./optparse.rb --local --code -a ARG0 ARG1 ARG2` 
  end

  def test_options_with_value
     assert_equal "{:local=>true, :value=>3}\n", `./optparse.rb -lv 3`
     assert_equal "{:local=>true, :pair=>[12, 0]}\n", `./optparse.rb -lp 12 34`
     assert_equal "{:local=>true, :novalue=>true}\n", `./optparse.rb -ln 12 `
  end
 
end
#!/usr/bin/env ruby
#argc.rb
puts ARGV.size
#!/usr/bin/env ruby
#optparse.rb
require "optparse"

def process_args
  options = {}
  OptionParser.new do |opts|
    opts.banner = "validate-url options:"
    opts.on '-h', '--help', 'Display this help' do
      puts opts
      exit
    end
    opts.on '-l', '--local', 'from local file' do
      options[:local] = true
    end
    opts.on '-c', '--code', 'print out response code' do
      options[:code] = true
    end
    opts.on '-a', '--argc', 'print out ARGV.size' do
      options[:argc] = true
    end
    opts.on '-v', '--value VALUE', 'option with value' do |v|
      options[:value] = v.to_i
    end
    opts.on '-p', '--position X Y', 'option with 2 values' do |x, y|
      options[:pair] = [x.to_i, y.to_i]
    end
    opts.on '-n', '--novalue', 'option with 2 values' do |x|
      options[:novalue] = x
    end
 
    opts.parse!
  end
  options
end

def main
  options = process_args
  puts (options[:argc])? ARGV.size : options
end

main