Using ruby's OptionParser to parse sub-commands

后端 未结 4 1200
情话喂你
情话喂你 2021-01-31 04:39

I\'d like to be able to use ruby\'s OptionParser to parse sub-commands of the form

COMMAND [GLOBAL FLAGS] [SUB-COMMAND [SUB-COMMAND FLAGS]]

lik

4条回答
  •  生来不讨喜
    2021-01-31 04:51

    Figured it out. I need to use OptionParser#order!. It will parse all the options from the start of ARGV until it finds a non-option (that isn't an option argument), removing everything it processes from ARGV, and then it will quit.

    So I just need to do something like:

    global = OptionParser.new do |opts|
      # ...
    end
    subcommands = { 
      'foo' => OptionParser.new do |opts|
         # ...
       end,
       # ...
       'baz' => OptionParser.new do |opts|
         # ...
       end
     }
    
     global.order!
     subcommands[ARGV.shift].order!
    

提交回复
热议问题