Class: Opt::Switch
- Inherits:
-
Object
- Object
- Opt::Switch
- Defined in:
- lib/opt/switch.rb
Overview
A single command line switch.
Constant Summary collapse
- REGEXP =
Regular expression matching an accepted command line switch
/\A(?<dash>--?)(?<name>[[:word:]]+([[[:word:]]-]*[[:word:]])?)\z/
Instance Attribute Summary collapse
-
#name ⇒ Object
readonly
Switch name.
Class Method Summary collapse
-
.new(object) ⇒ Object
Create new command line switch.
-
.parse(object) ⇒ Object
Parse an object or string into a Set of switches.
Instance Method Summary collapse
- #eql?(object) ⇒ Boolean
- #hash ⇒ Object
-
#initialize(str) ⇒ Switch
constructor
A new instance of Switch.
- #long? ⇒ Boolean
- #match!(argv) ⇒ Object
- #match?(argv) ⇒ Boolean
- #short? ⇒ Boolean
Constructor Details
#initialize(str) ⇒ Switch
Returns a new instance of Switch.
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# 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 |
Instance Attribute Details
#name ⇒ Object (readonly)
Switch name.
51 52 53 |
# File 'lib/opt/switch.rb', line 51 def name @name end |
Class Method Details
.new(object) ⇒ Object
Create new command line switch.
If a Switch object is given it will be returned instead.
34 35 36 37 38 39 40 |
# File 'lib/opt/switch.rb', line 34 def new(object) if object.is_a?(self) object else super object end end |
.parse(object) ⇒ Object
Parse an object or string into a Set of switches.
16 17 18 19 20 21 22 23 24 25 26 |
# 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 |
Instance Method Details
#eql?(object) ⇒ Boolean
80 81 82 83 84 85 86 |
# File 'lib/opt/switch.rb', line 80 def eql?(object) if object.is_a?(self.class) name == object.name else super end end |
#hash ⇒ Object
88 89 90 |
# File 'lib/opt/switch.rb', line 88 def hash name.hash end |
#long? ⇒ Boolean
76 77 78 |
# File 'lib/opt/switch.rb', line 76 def long? !short? end |
#match!(argv) ⇒ Object
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# 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) ⇒ Boolean
92 93 94 95 96 97 98 99 100 101 |
# 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? ⇒ Boolean
72 73 74 |
# File 'lib/opt/switch.rb', line 72 def short? @short end |