开发者

Printing list of only some options using Ruby OptionParser

开发者 https://www.devze.com 2023-04-06 05:24 出处:网络
My program has a lot of command line options. But I don\'t want to overwhelm the user when he types --help. Instead of printing out all options, I\'d like开发者_开发百科 to list only the most importan

My program has a lot of command line options. But I don't want to overwhelm the user when he types --help. Instead of printing out all options, I'd like开发者_开发百科 to list only the most important ones, printing the rest of them when one types --help=full.

But OptionParser seems to only support printing of the whole list of defined options. I'd like to write my own code that loops over the defined options and prints them out in my way, but OptionParser doesn't seem to provide any ways to access the options definitions it contains.

Is there a way to access the options in OptionParser that I may have missed? Or is there some good alternative to OptionParser? Or some other approach to this problem?


You could redefine the option --help for your need.

require 'optparse'

#create parsers
opts = OptionParser.new()
opts.banner = "Usage: example.rb [options]"
opts.separator("test optparse with --help[=full]")
opts.on("-v", "--[no-]verbose", "Run verbosely") { |v|
  puts "->Verbose ist #{v.inspect}"
}
opts.on("-r", "--repeat REPEAT", "Repeat REPEAT times") { |v|
  puts "->Repeat ist #{v.inspect}"
}

#Define your own --help
opts.on("-h", "--help [HELP]", "Help") { |v|
  case v
    when 'full' #write original help
      puts opts.help
    when nil, '' #write script specific help
      puts opts.banner 
      opts.summarize([], opts.summary_width ) { |helpline| 
        #make your own decision on each helpline
        #~ puts helpline #puts each line
        puts helpline unless helpline =~ /-v/ #ignore -v
      }
    else
      puts opts.banner 
      puts <<helpmessage
Undefined --help option. Please use 'full' or no option
  #{File.basename(__FILE__)} --help
  #{File.basename(__FILE__)} --help=full
helpmessage
  end
}

opts.parse!

In this version, --help shows all options, but not -v. You may make your own selection - or write a complete different help.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号