Class: Rclopts::RequiredArgOptionParser

Inherits:
OptionParser
  • Object
show all
Defined in:
lib/rclopts/required_arg_option_parser.rb

Defined Under Namespace

Classes: RequiredArgOptionParserError

Instance Method Summary collapse

Constructor Details

#initializeRequiredArgOptionParser

Returns a new instance of RequiredArgOptionParser.



9
10
11
12
# File 'lib/rclopts/required_arg_option_parser.rb', line 9

def initialize
  @required_arg_names = Set.new
  super
end

Instance Method Details

#on(*args, &block) ⇒ Object



32
33
34
35
36
# File 'lib/rclopts/required_arg_option_parser.rb', line 32

def on(*args, &block)
  super *args do |value|
    block.call(@options, value)
  end
end

#on_required(*args, &block) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rclopts/required_arg_option_parser.rb', line 14

def on_required(*args, &block)
  arg_name = nil
  args.each do |arg|
    if arg =~ /^((--\w+)(-\w+)*)/
      arg_name = $1
      break
    end
  end
  raise ArgumentError.new('Could not determine argument name') unless arg_name

  @required_arg_names << arg_name

  on *args do |options, value|
    @missing_arg_names.delete arg_name
    block.call(options, value)
  end
end

#on_tail(*args, &block) ⇒ Object



38
39
40
41
42
# File 'lib/rclopts/required_arg_option_parser.rb', line 38

def on_tail(*args, &block)
  super *args do
    block.call(@options)
  end
end

#process_args(args) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rclopts/required_arg_option_parser.rb', line 44

def process_args(args)
  @missing_arg_names = @required_arg_names.clone
  @options = OpenStruct.new
  free_args = args.clone

  begin
    parse!(free_args)
  rescue OptionParser::InvalidOption, OptionParser::MissingArgument
    message = $!.to_s + "\n\n" + self.to_s
    raise RequiredArgOptionParserError.new(message)
  end

  if !@missing_arg_names.empty?
    message = "missing required option: #{@missing_arg_names.to_a.sort.join(', ')}\n\n" + self.to_s
    raise RequiredArgOptionParserError.new(message)
  end

  [@options, free_args]
end