class Opt::Switch

A single command line switch.

Constants

REGEXP

Regular expression matching an accepted command line switch

Attributes

name[R]

Switch name.

Public Class Methods

new(object) click to toggle source

Create new command line switch.

If a Switch object is given it will be returned instead.

@see initialize

Calls superclass method
# File lib/opt/switch.rb, line 34
def new(object)
  if object.is_a?(self)
    object
  else
    super object
  end
end
new(str) click to toggle source
# File lib/opt/switch.rb, line 56
def initialize(str)
  match = REGEXP.match(str)
  raise "Invalid command line switch: #{str.inspect}" unless match

  @name  = match[:name].freeze

  case match[:dash].to_s.size
    when 0
      @short = name.size == 1
    when 1
      @short = true
    else
      @short = false
  end
end
parse(object) click to toggle source

Parse an object or string into a Set of switches.

@example

Opt::Switch.parse '-h, --help'
#=> Set{<Switch: -h>, <Switch: --help>}
# File lib/opt/switch.rb, line 16
def parse(object)
  if object.is_a?(self)
    object
  else
    if object.respond_to?(:to_str)
      parse_str object.to_str
    else
      parse_str object.to_s
    end
  end
end

Private Class Methods

parse_str(str) click to toggle source
# File lib/opt/switch.rb, line 44
def parse_str(str)
  Set.new str.split(/\s*,\s*/).map{|s| new s }
end

Public Instance Methods

eql?(object) click to toggle source
Calls superclass method
# File lib/opt/switch.rb, line 80
def eql?(object)
  if object.is_a?(self.class)
    name == object.name
  else
    super
  end
end
hash() click to toggle source
# File lib/opt/switch.rb, line 88
def hash
  name.hash
end
long?() click to toggle source
# File lib/opt/switch.rb, line 76
def long?
  !short?
end
match!(argv) click to toggle source
# File lib/opt/switch.rb, line 103
def match!(argv)
  return false unless match?(argv)

  if short? && argv.first.value.size > 1
    argv.first.value.slice!(0, 1)
  else
    arg = argv.shift

    if arg.value.include?('=')
      argv.unshift Command::Token.new(:text, arg.value.split('=', 2)[1])
    end
  end

  true
end
match?(argv) click to toggle source
# File lib/opt/switch.rb, line 92
def match?(argv)
  case (arg = argv.first).type
    when :long
      long? && arg.value.split('=')[0] == name
    when :short
      short? && arg.value[0] == name[0]
    else
      false
  end
end
short?() click to toggle source
# File lib/opt/switch.rb, line 72
def short?
  @short
end