Module: Opts

Defined in:
lib/Olib/opts.rb

Overview

minimal options parser

Constant Summary collapse

FLAG_PREFIX =
"--"

Class Method Summary collapse

Class Method Details

.as_list(key) ⇒ Object



33
34
35
36
37
# File 'lib/Olib/opts.rb', line 33

def self.as_list(key)
  val = to_h.fetch(key.to_sym, [])
  val = [val] if val.is_a?(String)
  return val
end

.method_missing(method, *args) ⇒ Object



39
40
41
# File 'lib/Olib/opts.rb', line 39

def self.method_missing(method, *args)
  parse.send(method, *args)
end

.parse(args = ) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/Olib/opts.rb', line 22

def self.parse(args = Script.current.vars[1..-1])        
  OpenStruct.new(**args.to_a.reduce(Hash.new) do |opts, v|
    if v.start_with?(FLAG_PREFIX)
      Opts.parse_flag(opts, v)
    else
      Opts.parse_command(opts, v)
    end
    opts
  end)
end

.parse_command(h, c) ⇒ Object



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

def self.parse_command(h, c)
  h[c.to_sym] = true
end

.parse_flag(h, f) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/Olib/opts.rb', line 11

def self.parse_flag(h, f)
  (name, val) = f[2..-1].split("=")
  if val.nil?
    h[name.to_sym] = true
  else
    val = val.split(",")

    h[name.to_sym] = val.size == 1 ? val.first : val
  end
end