Class: GLI::Switch

Inherits:
CommandLineToken show all
Defined in:
lib/gli/switch.rb

Overview

Defines a command line switch

Direct Known Subclasses

Flag

Instance Attribute Summary

Attributes inherited from CommandLineToken

#aliases, #description, #long_description, #name

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from CommandLineToken

#<=>, #usage

Constructor Details

#initialize(names, description, long_desc = nil) ⇒ Switch

:nodoc:



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

def initialize(names,description,long_desc=nil)
  super(names,description,long_desc)
  @default_value = false
end

Class Method Details

.name_as_string(name) ⇒ Object



58
59
60
61
# File 'lib/gli/switch.rb', line 58

def self.name_as_string(name)
  string = name.to_s
  string.length == 1 ? "-#{string}" : "--#{string}"
end

Instance Method Details

#default_value=(default) ⇒ Object

Used only to configure what’s returned if we do not detect this switch on the command line This allows the configuration file to set a switch as always on



32
33
34
# File 'lib/gli/switch.rb', line 32

def default_value=(default)
  @default_value = default
end

#find_me(arg) ⇒ Object

Finds the switch in the given arg, returning the arg to keep. Returns an array of size 2:

index 0

true or false if the arg was found

index 1

the remaining arg to keep in the command line or nil to remove it



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/gli/switch.rb', line 40

def find_me(arg)
  if @names[arg]
    return [true,nil]
  end
  @names.keys.each() do |name|
    if name =~ /^-(\w)$/
      match_string = "^\\-(\\w*)#{$1}(\\w*)$"
      match_data = arg.match(match_string)
      if match_data
        # Note that if [1] and [2] were both empty 
        # we'd have returned above
        return [true, "-" + match_data[1] + match_data[2]]
      end
    end
  end
  [false]
end

#get_value!(args) ⇒ Object

Given the argument list, scans it looking for this switch returning true if it’s in the argumennt list (and removing it from the argument list)



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

def get_value!(args)
  idx = -1
  args.each_index do |index|
    result = find_me(args[index])
    if result[0]
      if result[1]
        args[index] = result[1]
      else
        args.delete_at index
      end
      return result[0]
    end
  end
  @default_value
end