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(name, commands, key: :command, default: nil) ⇒ Nested

Returns a new instance of Nested.



23
24
25
26
27
28
29
30
# File 'lib/samovar/nested.rb', line 23

def initialize(name, commands, key: :command, default: nil)
  @name = name
  @commands = commands
  @key = key
  
  # This is the default name [of a command], not the default command:
  @default = default
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



32
33
34
# File 'lib/samovar/nested.rb', line 32

def key
  @key
end

Instance Method Details

#parse(input, default) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/samovar/nested.rb', line 56

def parse(input, default)
  if command = @commands[input.first]
    input.shift
    
    # puts "Instantiating #{command} with #{input}"
    command.new(input)
  elsif @default
    default || @commands[@default].new(input)
  end
end

#to_aObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/samovar/nested.rb', line 38

def to_a
  usage = [@name]
  
  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}"
  end
  
  return usage
end

#to_sObject



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

def to_s
  @name
end

#usage(rows) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/samovar/nested.rb', line 67

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