Class: Strop::Optdecl

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

Overview

Option declaration: names, argument requirement, and canonical label (auto-determined) Optdecl[:f, :foo, arg: :may] #=> Optdecl(names: [“f”, “foo”], arg: :may, label: “foo”)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(names:, arg: nil) ⇒ Optdecl

Returns a new instance of Optdecl.



15
16
17
18
19
20
21
22
# File 'lib/strop.rb', line 15

def initialize(names:, arg: nil)
  names = [*names].map{ Strop.name_from_symbol it }       # :foo_bar to "foo-bar" for symbols
  names[0] = names[0].sub(/[!?]$/, "") unless arg         # opt? / opt! to opt, and... (unless arg given)
  arg ||= { ?? => :may, ?! => :must }[$&] || :shant       # use ?/! to determine arg (unless arg given)
  label = names.find{ it.size > 1 } || names.first        # the canonical name used to search for it
  i[must may shant].member? arg or raise "invalid arg"   # validate arg
  super names:, arg:, label:
end

Instance Attribute Details

#argObject (readonly)

Returns the value of attribute arg

Returns:

  • (Object)

    the current value of arg



13
14
15
# File 'lib/strop.rb', line 13

def arg
  @arg
end

#labelObject (readonly)

Returns the value of attribute label

Returns:

  • (Object)

    the current value of label



13
14
15
# File 'lib/strop.rb', line 13

def label
  @label
end

#namesObject (readonly)

Returns the value of attribute names

Returns:

  • (Object)

    the current value of names



13
14
15
# File 'lib/strop.rb', line 13

def names
  @names
end

Class Method Details

.[](*names, arg: nil) ⇒ Object

Custom builder: Optdecl[names, …, arg: …]



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

def self.[](*names, arg: nil) = new(names:, arg:) # Custom builder: Optdecl[names, ..., arg: ...]

Instance Method Details

#arg!Object

requires arg



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

def arg! = self.arg == :must  # requires arg

#arg?Boolean

accepts arg

Returns:

  • (Boolean)


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

def arg? = self.arg != :shant # accepts arg

#no?Boolean

is a flag like –[no-]foo, –[no]bar

Returns:

  • (Boolean)


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

def no?  = names.each_cons(2).any?{|a,b| b =~ /\Ano-?#{Regexp.escape a}\z/ } # is a flag like --[no-]foo, --[no]bar

#to_sObject



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

def to_s = names.map{ Strop.prefix it }.join(", ") + { must: " X", may: " [X]", shant: "" }[arg]