Class: Strop::Optlist

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

Overview

List of option declarations with lookup via #[]. Used by ‘parse`. Generated by `parse_help` Optlist[decl1, decl2] #=> [Optdecl(…), Optdecl(…)]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_help(doc) ⇒ Object

a list of Optdecls



33
# File 'lib/strop.rb', line 33

def self.from_help(doc) = Strop.parse_help(doc) #=> Optlist[decl, ...] # Build from help text

Instance Method Details

#[](k) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/strop.rb', line 35

def [](k, ...)
  case k
  in String | Symbol
    s = Strop.name_from_symbol k
    found = find{ it.names.member? s } and return found
    found, *others = select{ it.names.any?{ it.start_with? s }} if s[1]
    found if found && others.empty?
  else super(k, ...)
  end
end

#to_s(as = :plain) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/strop.rb', line 46

def to_s(as=:plain)
  case as
  when :plain then join("\n")
  when :case
    caseins = map{|os| "in label: #{os.label.inspect}".tap{ it << ", value:" if os.arg? }}
    len = caseins.map(&:size).max
    caseins = caseins.zip(self).map{ |s,o| s.ljust(len) + " then#{' opt.no?' if o.no?} # #{o}" }
    <<~RUBY
      for item in Strop.parse!(optlist)
        case item
        #{caseins.map{ "  #{it}" }.join("\n").lstrip}
        in arg: then # positional
        in Strop::Sep then break # if you want to handle result.rest separately
        else raise "Unhandled result \#{item}"
        end
      end
    RUBY
  end
end