class Imperium::APIObject
Base class for handling data coming from the Consul API
Attributes
attribute_map[R]
The mapping of attribute names coming from Consul to names that are more Ruby friendly @return [Hash<String => Symbol>]
ruby_attribute_names[R]
The Ruby friendly names from {attribute_map} @return [Array<Symbol>]
Public Class Methods
attribute_map=(val)
click to toggle source
# File lib/imperium/api_object.rb, line 17 def attribute_map=(val) @attribute_map = val @ruby_attribute_names = val.values.map(&:to_sym) attr_accessor *@ruby_attribute_names end
new(attributes = {})
click to toggle source
Initialize a new object extracting attributes from the supplied hash
# 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
Public Instance Methods
==(other)
click to toggle source
# 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_map()
click to toggle source
# File lib/imperium/api_object.rb, line 37 def attribute_map self.class.attribute_map end
ruby_attribute_names()
click to toggle source
Shortcut method to access the class level attribute @return [Array<Symbol>]
# 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)
click to toggle source
Convert the object and any sub-objects into a hash
@param consul_names_as_keys [Boolean] Use the Consul object attribute names
as the keys when true (default) otherwise use the ruby attribute names.
# 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
Private Instance Methods
fancy_send_to_h(obj, consul_names)
click to toggle source
# File lib/imperium/api_object.rb, line 79 def fancy_send_to_h(obj, consul_names) (obj.is_a?(APIObject) ? obj.to_h(consul_names_as_keys: consul_names) : obj.to_h) end
maybe_hashified_attribute(attr_name, consul_names)
click to toggle source
# File lib/imperium/api_object.rb, line 65 def maybe_hashified_attribute(attr_name, consul_names) val = send(attr_name) if val.nil? nil elsif val.is_a?(Array) val.map { |elem| elem.respond_to?(:to_h) ? fancy_send_to_h(elem, consul_names) : elem } elsif val.respond_to?(:to_h) fancy_send_to_h(val, consul_names) else val end end