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

前端 未结 8 2123
时光取名叫无心
时光取名叫无心 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:26

    The idea is to define an OptionParser, then parse! it, and puts it if some fields are missing. Setting filename to empty string by default is probably not the best way to go, but you got the idea.

    require 'optparse'
    
    filename = ''
    options = OptionParser.new do |opts|
        opts.banner = "Usage: swift-code-style.rb [options]"
    
        opts.on("-iNAME", "--input-filename=NAME", "Input filename") do |name|
            filename = name
        end
        opts.on("-h", "--help", "Prints this help") do
            puts opts
            exit
        end
    end
    
    options.parse!
    
    if filename == ''
        puts "Missing filename.\n---\n"
        puts options
        exit
    end
    
    puts "Processing '#{filename}'..."
    

    If -i filename is missing, it displays:

    ~/prj/gem/swift-code-kit ./swift-code-style.rb
    Missing filename.
    ---
    Usage: swift-code-style.rb [options]
        -i, --input-filename=NAME        Input filename
        -h, --help                       Prints this help
    

提交回复
热议问题