module Pechkin::CLIHelper
Helper methods to declare all command line options. This should remove most optparse configuration boilerplate
Public Instance Methods
opt(name, default: nil, names:, desc: '', type: nil)
click to toggle source
@param name [Symbol] variable name to store values @opt default [Object] default value @opt names [Array<String>] list of command line keys @opt desc [String] option description @opt type [Class] argument type to parse from command line, e.g. Integer
# File lib/pechkin/cli.rb, line 16 def opt(name, default: nil, names:, desc: '', type: nil) @cli_options ||= [] # raise ':names is nil or empty' if names.nil? || names.empty? @cli_options << { name: name, default: default, names: names, type: type, desc: desc } end
parse(args)
click to toggle source
# File lib/pechkin/cli.rb, line 37 def parse(args) values = OpenStruct.new parser = parser_create(values) parser.parse(args) new.post_init(values) end
parser_create(values)
click to toggle source
# File lib/pechkin/cli.rb, line 45 def parser_create(values) parser = OptionParser.new parser.banner = @cli_banner (@cli_options || []).each do |o| if o.is_a?(String) parser.separator o else values[o[:name]] = o[:default] if o[:default] args = [] args += o[:names] args << o[:type] if o[:type] args << o[:desc] if o[:desc] parser.on(*args) { |v| values[o[:name]] = v } end end parser_create_default_opts(parser) parser end
parser_create_default_opts(parser)
click to toggle source
# File lib/pechkin/cli.rb, line 69 def parser_create_default_opts(parser) parser.separator '' parser.separator 'Common options:' parser.on_tail('-h', '--help', 'Show this message') do puts parser exit 1 end # Another typical switch to print the version. parser.on_tail('--version', 'Show version') do puts Version.version_string exit 0 end end
separator(string)
click to toggle source
# File lib/pechkin/cli.rb, line 28 def separator(string) @cli_options ||= [] @cli_options << string end