Class: Imperium::APIObject

Inherits:
Object
  • Object
show all
Defined in:
lib/imperium/api_object.rb

Overview

Base class for handling data coming from the Consul API

Direct Known Subclasses

Catalog::Service, KVPair, Service, ServiceCheck

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ APIObject

Initialize a new object extracting attributes from the supplied hash



25
26
27
28
29
30
# File 'lib/imperium/api_object.rb', line 25

def initialize(attributes = {})
  self.class.attribute_map.each do |key, attribute_name|
    value = attributes[attribute_name] || attributes[key]
    send("#{attribute_name}=", value) if value
  end
end

Class Attribute Details

.attribute_mapHash<String => Symbol>

The mapping of attribute names coming from Consul to names that are more Ruby friendly

Returns:

  • (Hash<String => Symbol>)


11
12
13
# File 'lib/imperium/api_object.rb', line 11

def attribute_map
  @attribute_map
end

.ruby_attribute_namesArray<Symbol> (readonly)

The Ruby friendly names from attribute_map

Returns:

  • (Array<Symbol>)


15
16
17
# File 'lib/imperium/api_object.rb', line 15

def ruby_attribute_names
  @ruby_attribute_names
end

Instance Method Details

#==(other) ⇒ Object



32
33
34
35
# File 'lib/imperium/api_object.rb', line 32

def ==(other)
  return false unless self.class == other.class
  ruby_attribute_names.all? { |attr| self.send(attr) == other.send(attr) }
end

#attribute_mapObject



37
38
39
# File 'lib/imperium/api_object.rb', line 37

def attribute_map
  self.class.attribute_map
end

#ruby_attribute_namesArray<Symbol>

Shortcut method to access the class level attribute

Returns:

  • (Array<Symbol>)


43
44
45
# File 'lib/imperium/api_object.rb', line 43

def ruby_attribute_names
  self.class.ruby_attribute_names
end

#to_h(consul_names_as_keys: true) ⇒ Object

Convert the object and any sub-objects into a hash

Parameters:

  • consul_names_as_keys (Boolean) (defaults to: true)

    Use the Consul object attribute names as the keys when true (default) otherwise use the ruby attribute names.



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/imperium/api_object.rb', line 51

def to_h(consul_names_as_keys: true)
  if consul_names_as_keys
    attribute_map.each_with_object({}) do |(consul, ruby), h|
      h[consul] = maybe_hashified_attribute(ruby, true)
    end.compact
  else
    ruby_attribute_names.each_with_object({}) do |attr, h|
      h[attr] = maybe_hashified_attribute(attr, false)
    end.compact
  end
end