Class: Samovar::Flag

Inherits:
Object
  • Object
show all
Defined in:
lib/samovar/flags.rb

Overview

Represents a single command-line flag.

A flag can be a simple boolean flag or a flag that accepts a value.

Direct Known Subclasses

BooleanFlag, ValueFlag

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text, prefix, alternatives = nil) ⇒ Flag

Initialize a new flag.



111
112
113
114
115
# File 'lib/samovar/flags.rb', line 111

def initialize(text, prefix, alternatives = nil)
	@text = text
	@prefix = prefix
	@alternatives = alternatives
end

Instance Attribute Details

#alternativesObject (readonly)

Alternative flag prefixes.



130
131
132
# File 'lib/samovar/flags.rb', line 130

def alternatives
  @alternatives
end

#prefixObject (readonly)

The primary flag prefix.



125
126
127
# File 'lib/samovar/flags.rb', line 125

def prefix
  @prefix
end

#textObject (readonly)

The full flag specification text.



120
121
122
# File 'lib/samovar/flags.rb', line 120

def text
  @text
end

Class Method Details

.parse(text) ⇒ Object

Parse a flag specification string into a flag instance.



96
97
98
99
100
101
102
103
104
# File 'lib/samovar/flags.rb', line 96

def self.parse(text)
	if text =~ /(.*?)\s(\<.*?\>)/
		ValueFlag.new(text, $1, $2)
	elsif text =~ /--\[no\]-(.*?)$/
		BooleanFlag.new(text, "--#{$1}")
	else
		ValueFlag.new(text, text, nil)
	end
end

Instance Method Details

#boolean?Boolean

Whether this is a boolean flag.

Returns:

  • (Boolean)


149
150
151
# File 'lib/samovar/flags.rb', line 149

def boolean?
	false
end

#completionsObject

The possible flag prefixes for completion.



164
165
166
# File 'lib/samovar/flags.rb', line 164

def completions
	[@prefix, *@alternatives]
end

#keyObject

Generate a key name for this flag.



142
143
144
# File 'lib/samovar/flags.rb', line 142

def key
	@key ||= @prefix.sub(/^-*/, "").gsub("-", "_").to_sym
end

#prefix?(token) ⇒ Boolean

Check if the token matches this flag.

Returns:

  • (Boolean)


157
158
159
# File 'lib/samovar/flags.rb', line 157

def prefix?(token)
	@prefix == token or @alternatives&.include?(token)
end

#to_sObject

Generate a string representation for usage output.



135
136
137
# File 'lib/samovar/flags.rb', line 135

def to_s
	@text
end