Module: Thunder::OptParseAdapter

Defined in:
lib/thunder/options/optparse.rb

Overview

Provides an adapter to the optparse library included in the Ruby std-lib

Class Method Summary collapse

Class Method Details

.process_options(args, command_spec) ⇒ Object

See Also:

  • Thunder#process_options


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/thunder/options/optparse.rb', line 6

def self.process_options(args, command_spec)
  return {} unless command_spec[:options]

  options = {}
  command_spec[:options_processor] ||= OptionParser.new do |parser|
    command_spec[:options].each do |name, option_spec|
      opt = []
      opt << "-#{option_spec[:short]}"
      opt << if option_spec[:type] == Boolean
        "--[no-]#{name}"
      else
        "--#{name} [#{name.to_s.upcase}]"
      end
      opt << option_spec[:type] unless option_spec[:type] == Boolean
      opt << option_spec[:desc]
      parser.on(*opt) do |value|
        options[name] = value
      end
    end
  end
  command_spec[:options_processor].parse!(args)

  # set default values
  command_spec[:options].each do |name, option_spec|
    next if options.has_key? name
    next unless option_spec[:default]
    options[name] = option_spec[:default]
  end

  return options
rescue OptionParser::InvalidOption => e
  puts e
  puts "Try --help for help."
  exit 1
end