Class: GLI::Flag

Inherits:
Switch show all
Defined in:
lib/gli/flag.rb

Overview

Defines a flag, which is to say a switch that takes an argument

Instance Attribute Summary collapse

Attributes inherited from CommandLineToken

#aliases, #description, #long_description, #name

Instance Method Summary collapse

Methods inherited from Switch

name_as_string

Methods inherited from CommandLineToken

#<=>, #usage

Constructor Details

#initialize(names, description, argument_name = nil, default = nil, long_desc = nil) ⇒ Flag

Returns a new instance of Flag.



10
11
12
13
14
# File 'lib/gli/flag.rb', line 10

def initialize(names,description,argument_name=nil,default=nil,long_desc=nil)
  super(names,description,long_desc)
  @argument_name = argument_name || "arg"
  @default_value = default
end

Instance Attribute Details

#default_valueObject

:nodoc:



8
9
10
# File 'lib/gli/flag.rb', line 8

def default_value
  @default_value
end

Instance Method Details

#all_forms(joiner = ', ') ⇒ Object

Returns a string of all possible forms of this flag. Mostly intended for printing to the user.



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/gli/flag.rb', line 55

def all_forms(joiner=', ')
  forms = all_forms_a
  string = forms.join(joiner)
  if forms[-1] =~ /^\-\-/
    string += '='
  else
    string += ' '
  end
  string += @argument_name
  return string
end

#find_me(arg) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/gli/flag.rb', line 38

def find_me(arg)
  if @names[arg]
    return [true,arg,nil] if arg.length == 2
    # This means we matched the long-form, but there's no argument
    raise BadCommandLine.new("#{arg} requires an argument via #{arg}=argument")
  end
  @names.keys.each() do |name|
    match_string = "^#{name}=(.*)$"
    match_data = arg.match(match_string)
    return [true,name,$1] if match_data;
  end
  [false,nil,nil]
end

#get_value!(args) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/gli/flag.rb', line 16

def get_value!(args)
  args.each_index() do |index|
    arg = args[index]
    present,matched,value = find_me(arg)
    if present
      args.delete_at index
      if !value || value == ''
        if args[index]
          value = args[index]
          args.delete_at index
          return value
        else
          raise BadCommandLine.new("#{matched} requires an argument")
        end
      else
        return value
      end
    end
  end
  return @default_value
end