class Nested
Represents nested sub-commands in a command.
A Nested
parser allows you to define multiple sub-commands that can be invoked from the parent command.
Definitions
def initialize(key, commands, default: nil, required: false)
Initialize a new nested command parser.
Signature
-
parameter
key
Symbol
The name of the attribute to store the selected command in.
-
parameter
commands
Hash
A mapping of command names to command classes.
-
parameter
default
String | Nil
The default command name if none is provided.
-
parameter
required
Boolean
Whether a command is required.
Implementation
def initialize(key, commands, default: nil, required: false)
@key = key
@commands = commands
# This is the default name [of a command], not the default command:
@default = default
@required = required
end
attr :key
The name of the attribute to store the selected command in.
Signature
-
attribute
Symbol
attr :commands
A mapping of command names to command classes.
Signature
-
attribute
Hash
attr :default
The default command name if none is provided.
Signature
-
attribute
String | Nil
attr :required
Whether a command is required.
Signature
-
attribute
Boolean
def to_s
Generate a string representation for usage output.
Signature
-
returns
String
The usage string.
Implementation
def to_s
"<#{@key}>"
end
def to_a
Generate an array representation for usage output.
Signature
-
returns
Array
The usage array.
Implementation
def to_a
usage = [self.to_s]
if @commands.size == 0
usage << "No commands available."
elsif @commands.size == 1
usage << "Only #{@commands.first}."
else
usage << "One of: #{@commands.keys.join(', ')}."
end
if @default
usage << "(default: #{@default})"
elsif @required
usage << "(required)"
end
return usage
end
def parse(input, parent = nil, default = nil)
Parse a nested command from the input.
Signature
-
parameter
input
Array(String)
The command-line arguments.
-
parameter
parent
Command | Nil
The parent command.
-
parameter
default
Command | Nil
The default command instance.
-
returns
Command | Object | Nil
The parsed command instance, or the default if no match.
Implementation
def parse(input, parent = nil, default = nil)
if command = @commands[input.first]
name = input.shift
# puts "Instantiating #{command} with #{input}"
command.new(input, name: name, parent: parent)
elsif default
return default
elsif @default
@commands[@default].new(input, name: @default, parent: parent)
elsif @required
raise MissingValueError.new(parent, @key)
end
end
def usage(rows)
Generate usage information for this nested command.
Signature
-
parameter
rows
Output::Rows
The rows to append usage information to.
Implementation
def usage(rows)
rows << self
@commands.each do |key, klass|
klass.usage(rows, key)
end
end