class Option

Command option encapsulation

Attributes

allowed[RW]
desc[R]
hint[R]
key[R]
long[R]
required[RW]
short[R]
type[R]

Public Class Methods

new(key, desc, type:nil, required:false, allowed:{}) click to toggle source

Create a new option instance @param key [String] option short hand, long hand and hint e.g. -s|–skip=COMPONENTS @param desc [String] the option's description @param type [Type] the option's type @param required [Bool] require the option if true else optional @param allowed [Hash] hash of allowed strings to descriptions maps

# File lib/nub/commander.rb, line 44
def initialize(key, desc, type:nil, required:false, allowed:{})
  @hint = nil
  @long = nil
  @short = nil
  @desc = desc
  @allowed = allowed || {}
  @required = required || false
  Log.die("allowed should be a hash of values to descriptions") if allowed.class != Hash
  Log.die("required should be a boolean value") if ![TrueClass, FalseClass].include?(required.class)

  # Parse the key into its components (short hand, long hand, and hint)
  #https://bneijt.nl/pr/ruby-regular-expressions/
  # Valid forms to look for with chars [a-zA-Z0-9-_=|]
  # --help, --help=HINT, -h|--help, -h|--help=HINT
  Log.die("invalid option key #{key}") if key && (key.count('=') > 1 or key.count('|') > 1 or !key[/[^\w\-=|]/].nil? or
    key[/(^--[a-zA-Z0-9\-_]+$)|(^--[a-zA-Z\-_]+=\w+$)|(^-[a-zA-Z]\|--[a-zA-Z0-9\-_]+$)|(^-[a-zA-Z]\|--[a-zA-Z0-9\-_]+=\w+$)/].nil?)
  @key = key
  if key
    @hint = key[/.*=(.*)$/, 1]
    @short = key[/^(-\w).*$/, 1]
    @long = key[/(--[\w\-]+)(=.+)*$/, 1]
  end

  # Convert true/false to TrueClass/FalseClass
  type = TrueClass if type.class == TrueClass
  type = FalseClass if type.class == FalseClass

  # Validate and set type, allow Flag defaults to be true or false
  Log.die("invalid option type #{type}") if ![String, Integer, Array, TrueClass, FalseClass, nil].any?{|x| type == x}
  Log.die("option type must be set") if @hint && !type
  @type = String if !key && !type
  @type = FalseClass if key and !type
  @type = type if type

  # Validate hint is given for non flags
  Log.die("option hint must be set") if @key && !@hint && @type != FalseClass && @type != TrueClass

  # Validate allowed
  if @allowed.any?
    allowed_type = @allowed.first.first.class
    Log.die("mixed allowed types") if @allowed.any?{|k,v| k.class != allowed_type}
  end
end

Public Instance Methods

to_s(level:0) click to toggle source

Return a human readable string of this object @param level [Integer] level to indent

# File lib/nub/commander.rb, line 96
def to_s(level:0)
  return "#{" " * level * 2}Option => key:#{@key}, desc:'#{@desc}', type:#{@type}, allowed:#{@allowed}, required:#{@required}"
end
to_sym() click to toggle source

Get a symbol representing the command @returns symbol

# File lib/nub/commander.rb, line 90
def to_sym
  return @long[2..-1].gsub("-", "_").to_sym
end