Class: Samovar::Nested

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

Overview

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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, commands, default: nil, required: false) ⇒ Nested

Initialize a new nested command parser.



17
18
19
20
21
22
23
24
25
# File '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

Instance Attribute Details

#commandsObject

A mapping of command names to command classes.



35
36
37
# File 'lib/samovar/nested.rb', line 35

def commands
  @commands
end

#defaultObject (readonly)

The default command name if none is provided.



40
41
42
# File 'lib/samovar/nested.rb', line 40

def default
  @default
end

#keyObject

The name of the attribute to store the selected command in.



30
31
32
# File 'lib/samovar/nested.rb', line 30

def key
  @key
end

#requiredObject

Whether a command is required.



45
46
47
# File 'lib/samovar/nested.rb', line 45

def required
  @required
end

Instance Method Details

#parse(input, parent = nil, default = nil) ⇒ Object

Parse a nested command from the input.



83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File '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

#to_aObject

Generate an array representation for usage output.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File '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

#to_sObject

Generate a string representation for usage output.



50
51
52
# File 'lib/samovar/nested.rb', line 50

def to_s
	"<#{@key}>"
end

#usage(rows) ⇒ Object

Generate usage information for this nested command.



101
102
103
104
105
106
107
# File 'lib/samovar/nested.rb', line 101

def usage(rows)
	rows << self
	
	@commands.each do |key, klass|
		klass.usage(rows, key)
	end
end