Class: MVCLI::Argv

Inherits:
Object
  • Object
show all
Defined in:
lib/mvcli/argv.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv, switches = []) ⇒ Argv

Returns a new instance of Argv.



6
7
8
9
# File 'lib/mvcli/argv.rb', line 6

def initialize(argv, switches = [])
  @switches = switches.map(&:to_s)
  @arguments, @options = scan argv
end

Instance Attribute Details

#argumentsObject (readonly)

Returns the value of attribute arguments.



4
5
6
# File 'lib/mvcli/argv.rb', line 4

def arguments
  @arguments
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/mvcli/argv.rb', line 4

def options
  @options
end

Instance Method Details

#merge(options, key, value = nil) ⇒ Object



39
40
41
42
43
# File 'lib/mvcli/argv.rb', line 39

def merge(options, key, value = nil)
  key = underscore key
  values = options[key] || []
  options.merge(key => values + [value].compact)
end

#scan(argv, arguments = [], options = Map.new) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mvcli/argv.rb', line 11

def scan(argv, arguments = [], options = Map.new)
  current, *rest = argv
  case current
  when nil
    [arguments, options]
  when /^--(\w[[:graph:]]+)=([[:graph:]]+)$/
    scan rest, arguments, merge(options, $1, $2)
  when /^--no-(\w[[:graph:]]+)$/
    scan rest, arguments, merge(options, $1, false)
  when /^--(\w[[:graph:]]+)$/, /^-(\w)$/
    key = underscore $1
    if switch? key
      scan rest, arguments, merge(options, key, true)
    elsif rest.first =~ /^-/
      scan rest, arguments, merge(options, key)
    else
      value, *rest = rest
      scan rest, arguments, merge(options, key, value)
    end
  else
    scan rest, arguments + [current], options
  end
end

#switch?(key) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/mvcli/argv.rb', line 35

def switch?(key)
  @switches.member? underscore key
end

#underscore(string) ⇒ Object



45
46
47
# File 'lib/mvcli/argv.rb', line 45

def underscore(string)
  string.gsub('-','_')
end