Class: TextFSM::CliTable

Inherits:
Table
  • Object
show all
Defined in:
lib/textfsm/cli_table.rb

Instance Attribute Summary collapse

Attributes inherited from Table

#header, #rows

Instance Method Summary collapse

Methods inherited from Table

#[], #each, #empty?, #merge, #merge!, #size, #sort!, #sort_by!, #to_a, #to_hashes, #to_s

Constructor Details

#initialize(index: nil, template_dir: ".") ⇒ CliTable

Returns a new instance of CliTable.



13
14
15
16
17
18
# File 'lib/textfsm/cli_table.rb', line 13

def initialize(index: nil, template_dir: ".")
  super()
  @template_dir = File.path(template_dir).dup.freeze
  @keys = [].freeze
  load_index(index) if index
end

Instance Attribute Details

#index ⇒ Object (readonly)

Returns the value of attribute index.



11
12
13
# File 'lib/textfsm/cli_table.rb', line 11

def index
  @index
end

#input ⇒ Object (readonly)

Returns the value of attribute input.



11
12
13
# File 'lib/textfsm/cli_table.rb', line 11

def input
  @input
end

#keys ⇒ Object

Returns the value of attribute keys.



11
12
13
# File 'lib/textfsm/cli_table.rb', line 11

def keys
  @keys
end

#template_dir ⇒ Object (readonly)

Returns the value of attribute template_dir.



11
12
13
# File 'lib/textfsm/cli_table.rb', line 11

def template_dir
  @template_dir
end

Instance Method Details

#key_for(row) ⇒ Object



61
62
63
# File 'lib/textfsm/cli_table.rb', line 61

def key_for(row)
  row.values_at(*@keys.map { |key| @header.index(key) })
end

#load_index(path) ⇒ Object

Raises:



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/textfsm/cli_table.rb', line 20

def load_index(path)
  candidate = IndexTable.new(
    File.join(@template_dir, path),
    transform: ->(key, value) { key == "Command" ? expand_command(value) : value },
    compile: ->(key, value) { key == "Template" ? nil : value }
  )
  raise IndexError, "Index must contain a Template column" unless candidate.header.include?("Template")

  @index = candidate
  self
end

#parse(text, attributes: {}, templates: nil) ⇒ Object

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/textfsm/cli_table.rb', line 32

def parse(text, attributes: {}, templates: nil)
  names = template_names(templates || find_templates(attributes))
  text = text.read if text.respond_to?(:read)
  raise ArgumentError, "text must be a String or readable IO" unless text.is_a?(String)

  keys = []
  table = names.reduce(nil) do |result, name|
    parser = Parser.from_file(File.join(@template_dir, name))
    keys = parser.fields_with_option("Key") if keys.empty?
    parsed = Table.new(parser.header, parser.parse(text))
    result ? result.merge!(parsed, keys: keys) : parsed
  end
  # Replace the result only after every template and merge succeeds.
  input = text.dup.freeze
  keys = Data.copy(keys, immutable: true)
  @input = input
  @header = table.header
  @rows = table.rows
  @keys = keys
  self
end