Class: Args

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

Instance Method Summary collapse

Constructor Details

#initializeArgs

Returns a new instance of Args.



3
4
5
# File 'lib/args.rb', line 3

def initialize
  @args = {}
end

Instance Method Details

#add_arg(k, arity) ⇒ Object



7
8
9
# File 'lib/args.rb', line 7

def add_arg(k, arity)
  @args[k] = arity == 1 ? ":" : ""
end

#handle(output) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/args.rb', line 24

def handle(output)
  Hash.new.tap do |v|
    output.lines.each do |l|
      if l =~ /^(.)$/
        v[$1] = true
      elsif l =~ /^(.)==(.*)$/
        v[$1] = $2
      end
    end
  end
end

#parse(args) ⇒ Object



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

def parse(args)
  cmd = %<set -- #{args.map {|a| "\"#{a}\""}.join(" ")}; while getopts :#{to_getopts} arg; do\n>
  cmd << "case \"$arg\" in\n"
  @args.each do |k, v|
    cmd << "#{k}) echo #{k}"
    cmd << "==$OPTARG" if v == ":"
    cmd << ";;\n"
  end
  cmd << "esac; done"
  output = `#{cmd}`
  return handle(output)
end

#to_getoptsObject



36
37
38
39
40
# File 'lib/args.rb', line 36

def to_getopts
  @args.map do |k, v|
    "#{k}#{v}"
  end.join("")
end