class Samovar::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.
Attributes
A mapping of command names to command classes.
@attribute [Hash]
The default command name if none is provided.
@attribute [String | Nil]
The name of the attribute to store the selected command in.
@attribute [Symbol]
Whether a command is required.
@attribute [Boolean]
Public Class Methods
Source
# File vendor/bundle/ruby/3.4.0/gems/samovar-2.4.1/lib/samovar/nested.rb, line 17 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
Initialize a new nested command parser.
@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.
Public Instance Methods
Source
# File vendor/bundle/ruby/3.4.0/gems/samovar-2.4.1/lib/samovar/nested.rb, line 83 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
Parse a nested command from the input.
@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.
Source
# File vendor/bundle/ruby/3.4.0/gems/samovar-2.4.1/lib/samovar/nested.rb, line 57 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
Generate an array representation for usage output.
@returns [Array] The usage array.
Source
# File vendor/bundle/ruby/3.4.0/gems/samovar-2.4.1/lib/samovar/nested.rb, line 50 def to_s "<#{@key}>" end
Generate a string representation for usage output.
@returns [String] The usage string.
Source
# File vendor/bundle/ruby/3.4.0/gems/samovar-2.4.1/lib/samovar/nested.rb, line 101 def usage(rows) rows << self @commands.each do |key, klass| klass.usage(rows, key) end end
Generate usage information for this nested command.
@parameter rows [Output::Rows] The rows to append usage information to.