Class: ArgvParser

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

Instance Method Summary collapse

Constructor Details

#initializeArgvParser

Returns a new instance of ArgvParser.



3
4
5
6
7
8
# File 'lib/argv_parser.rb', line 3

def initialize
  @args = Hash.new
  @aliases = Hash.new
  @l_short = 0
  @l_long = 0
end

Instance Method Details

#helpObject



23
24
25
26
27
28
29
30
31
32
# File 'lib/argv_parser.rb', line 23

def help
  puts "Help:"
  @args.each do |k,v|
    spaces = ""
    (@l_short-k.length).times { spaces << " " }
    spaces2 = ""
    (@l_long-v[:long].length).times { spaces2 << " " }
    puts "#{k}#{spaces} #{v[:long]}#{spaces2} mandatory: #{v[:opts][:mandatory] == true}"
  end
end

#hook(short, long, type, options) ⇒ Object

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/argv_parser.rb', line 10

def hook(short, long, type, options)
  raise ArgumentError.new("short is nil") if not short

  @args[short.downcase] = {
    :long => long,
    :type => type,
    :opts => options,
    :yield => Proc.new {|p, v| yield(p, v) }
  }
  @l_short = short.length + 1 if @l_short < short.length + 1
  @l_long = long.length + 1 if @l_long < long.length + 1
end

#parse!(args) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/argv_parser.rb', line 34

def parse!(args)
  begin
  executor = Array.new
  i = 0

  @mandatory = Array.new
  @args.each do |k,v|
    @mandatory.push k if v[:opts][:mandatory]
  end

  while i < args.length
    if v = @args[args[i].downcase]
      @mandatory.delete args[i].downcase

      n = nil
      if v[:type]
        raise ArgumentError.new("argument for #{args[i].downcase} missing") if i+1 >= args.length
        i += 1
        case v[:type].to_s
          when "Array"
            n = args[i].split ','
          when "Float"
            n = args[i].to_f
          when "Integer"
            n = args[i].to_i
          else
            n = $1 if args[i] =~ /^\"?(.*)\"?$/
          end
      end
      executor.push [v[:yield], n]
    else
      raise ArgumentError.new("argument #{args[i].downcase} unknown")
    end
    i += 1
  end

  if not @mandatory.empty?
    raise ArgumentError.new("mandatory #{@mandatory[0]} is missing")
  end

  if executor.empty?
    help
  else
    executor.each do |e|
      e[0].call(self, e[1])
    end
  end
  rescue Exception => e
    puts "#{e.class}: #{e.message}\n"
    help
  end
end