Class: Nexpose::APIObject

Inherits:
Object
  • Object
show all
Defined in:
lib/nexpose/api.rb

Overview

Base class for all API 2.0 objects which are derived from JSON representations.

This class is not intended to be used by customers, but to extend functionality in the gem itself.

To use this class, do the following:

  • Subclass APIObject

  • Do NOT provide a constructor method, or it must take no arguments.

  • Clearly document all attributes which the customer can expect to see.

  • Clearly document those attributes which are lazily loaded.

  • If applicable, implement a load method which calls new.object_from_hash

Instance Method Summary collapse

Instance Method Details

#object_from_hash(nsc, hash) ⇒ Object

Populate object methods and attributes from a JSON-derived hash.

Parameters:

  • nsc (Nexpose::Connection)

    Active connection to a console.

  • hash (Hash)

    Result of running JSON#parse with the symbolize_names parameter to a 2.0 API response. Pass hash if the response is pageable.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/nexpose/api.rb', line 23

def object_from_hash(nsc, hash)
  hash.each do |k, v|
    next if k == :url # Do not store self-referential URL.
    # Store resource URLs separately and create lazy accessors.
    if v.is_a?(Hash) && v.key?(:url)
      self.class.send(:define_method, k, proc { |conn = nsc| load_resource(conn, k, v[:url].gsub(/.*\/api/, '/api')) })
    else
      # Convert timestamps.
      if v.is_a?(String) && v.match(/^\d{8}T\d{6}\.\d{3}/)
        instance_variable_set("@#{k}", ISO8601.to_time(v))
      elsif v.is_a?(Array) && k == :attributes
        instance_variable_set("@#{k}", v.map { |h| { h[:key] => h[:value] } })
      else
        instance_variable_set("@#{k}", v)
      end
      self.class.send(:define_method, k, proc { instance_variable_get("@#{k}") })
    end
  end
  self
end