Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

GetoptLongを使ってCLIのRubyアプリに引数を加える

CLIで使う場合、オプションがついてると何かと便利なケースがあります。
ARGVで必死になるのも良いですが、GetoptLongを使うと綺麗に書けます。
標準ライブラリなので、Ruby環境があればスグ使えるのも利点です。

require 'getoptlong'

opts = GetoptLong.new(
  [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
  [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
  [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
  case opt
    when '--help'
      puts <<-EOF
usage :: hello [OPTION] ... DIR

-h, --help:
   show help

--repeat x, -n x:
   repeat x times

--name [name]:
   greet user by name, if name not supplied default is John

DIR: The directory in which to issue the greeting.
      EOF
    when '--repeat'
      repetitions = arg.to_i
    when '--name'
      if arg == ''
        name = 'John'
      else
        name = arg
      end
  end
end

if ARGV.length != 1
  puts "Missing dir argument (try --help)"
  exit 0
end

dir = ARGV.shift

Dir.chdir(dir)
p `pwd`
(1..repetitions).each do
  puts "Hello,%s" % [name]
end

実行結果

$ ruby test_opt.rb -n 3 --name shuzo -- /tmp
test_opt.rb:48: warning: Insecure world writable dir /usr/local/Cellar in PATH, mode 040777
/private/tmp
Hello,shuzo
Hello,shuzo
Hello,shuzo