Class: Samovar::Nested

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Nested.



8
9
10
11
12
13
14
15
16
# File 'lib/samovar/nested.rb', line 8

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 (readonly)

Returns the value of attribute commands.



19
20
21
# File 'lib/samovar/nested.rb', line 19

def commands
  @commands
end

#defaultObject (readonly)

Returns the value of attribute default.



20
21
22
# File 'lib/samovar/nested.rb', line 20

def default
  @default
end

#keyObject (readonly)

Returns the value of attribute key.



18
19
20
# File 'lib/samovar/nested.rb', line 18

def key
  @key
end

#requiredObject (readonly)

Returns the value of attribute required.



21
22
23
# File 'lib/samovar/nested.rb', line 21

def required
  @required
end

Instance Method Details

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

Parameters:

  • default (Command) (defaults to: nil)

    the default command if any.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/samovar/nested.rb', line 48

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, self)
	end
end

#to_aObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/samovar/nested.rb', line 27

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



23
24
25
# File 'lib/samovar/nested.rb', line 23

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

#usage(rows) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/samovar/nested.rb', line 63

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