Method: Cisco::Client.filter_data

Defined in:
lib/cisco_node_utils/client/utils.rb

.filter_data(data: nil, keys: nil) ⇒ Object

Helper method for get(data_format: :nxapi_structured).

Parameters:

  • data (Array, Hash) (defaults to: nil)

    structured output from node

  • keys (Array) (defaults to: nil)

    lookup sequence



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/cisco_node_utils/client/utils.rb', line 141

def self.filter_data(data: nil,
                     keys: nil)
  return nil if data.nil? || data.empty?
  keys ||= []
  keys.each do |filter|
    # if filter is a Hash and data is an array, check each
    # array index (which should return another hash) to see if
    # it contains the matching key/value pairs specified in token,
    # and return the first match (or nil)
    if filter.kind_of?(Hash)
      fail "Expected Array, got #{data.class}" unless data.is_a? Array
      data = data.select { |x| filter.all? { |k, v| x[k] == v } }
      fail "Multiple matches found for #{filter}" if data.length > 1
      fail "No match found for #{filter}" if data.length == 0
      data = data[0]
    else # data is array or hash
      if data.is_a? Array
        final = []
        data.each do |row|
          final << row[filter]
        end
        return final
      end
      fail "No key \"#{filter}\" in #{data}" unless data.key?(filter)
      data = data[filter]
    end
  end
  data
end