How do you specify a required switch (not argument) with Ruby OptionParser?

前端 未结 8 2070
时光取名叫无心
时光取名叫无心 2020-12-12 23:58

I\'m writing a script and I want to require a --host switch with value, but if the --host switch isn\'t specified, I want the option parsing to fai

8条回答
  •  無奈伤痛
    2020-12-13 00:33

    I came up with a clear and concise solution that sums up your contributions. It raises an OptionParser::MissingArgument exception with the missing arguments as a message. This exception is catched in the rescue block along with the rest of exceptions coming from OptionParser.

    #!/usr/bin/env ruby
    require 'optparse'
    
    options = {}
    
    optparse = OptionParser.new do |opts|
      opts.on('-h', '--host hostname', "Host name") do |host|
        options[:host] = host
      end
    end
    
    begin
      optparse.parse!
      mandatory = [:host]
      missing = mandatory.select{ |param| options[param].nil? }
      raise OptionParser::MissingArgument, missing.join(', ') unless missing.empty?
    rescue OptionParser::ParseError => e
      puts e
      puts optparse
      exit
    end
    

    Running this example:

     ./program            
    missing argument: host
    Usage: program [options]
        -h, --host hostname              Host name
    

提交回复
热议问题