Module: Commandorobo::Utils

Included in:
Commandorobo
Defined in:
lib/util.rb

Overview

Utilities for commandorobo.

Class Method Summary collapse

Class Method Details

.consume_switch(str) ⇒ Hash

Gets switches from text.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/util.rb', line 17

def self.consume_switch(str)
    nextarg = nil
    parsed = false
    switches = {}
    ws = str.split(' ')
    ws.each_with_index do |k, i|
        parsed = false
        if k.start_with?('-') && k.length > 1
            # oh heck a switch

            if k[1] == '-'
                # oh heck another switch

                k = self.nodash(k)
                switches[k.to_sym] = ws[i+1].nil? && !ws[i+1].start_with?('-') ? true : ws[i+1]
            else
                # no double-switch: interpret literally

                k = self.nodash(k)
                if k.length == 1
                    switches[k.to_sym] = ws[i+1].nil? && !ws[i+1].start_with?('-') ? true : ws[i+1]
                else
                    k.chars.each do |l|
                        switches[l.to_sym] = true
                    end
                    switches[switches.keys.last] = ws[i+1].nil? && !ws[i+1].start_with?('-') ? true : ws[i+1]
                end
            end
        end
    end
    return switches
end

.nodash(i) ⇒ String

Removes dashes. Used internally.



10
11
12
# File 'lib/util.rb', line 10

def self.nodash(i)
    i.split('').reject {|j| j == '-'}.join('')
end

.remove_switch(str) ⇒ Array

Does the opposite of consume_switch, it removes switches.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/util.rb', line 50

def self.remove_switch(str)
    parsed = []
    skip = false
    str.split(' ').each do |i|
        if skip
            skip = false
            next
        end
        if i.start_with?('-') && i.length > 1
            skip = true
        else
            parsed << i
        end
    end
    parsed
end