class Nomad::Response

Constants

BUILTIN_LOADERS

Public Class Methods

decode(object) click to toggle source

Decodes the given object (usually a Hash) into an instance of this class.

@param object [Hash<Symbol, Object>] @return [Object, nil]

# File lib/nomad/response.rb, line 75
def self.decode(object)
  return nil if object.nil?
  self.new(object)
end
field(n, opts = {}) click to toggle source

Defines a new field. This is designed to be used by the subclass as a mini-DSL.

@example Default

field :data

@example With a mutator

field :present, as: :present?

@param n [Symbol] the name of the field @option opts [Symbol] :as alias for method name @option opts [Symbol] :load custom loader/parser for data

@!visibility private

# File lib/nomad/response.rb, line 58
def self.field(n, opts = {})
  self.fields[n] = opts

  opts[:as] = (opts[:as] || n).to_sym
  attr_reader opts[:as]
end
fields() click to toggle source

Returns the list of fields defined on this subclass. @!visibility private

# File lib/nomad/response.rb, line 67
def self.fields
  @fields ||= {}
end
new(input = {}) click to toggle source
# File lib/nomad/response.rb, line 80
def initialize(input = {})
  # Initialize all fields as nil to start
  self.class.fields.each do |n, opts|
    instance_variable_set(:"@#{opts[:as]}", nil)
  end

  # For each supplied option, set the instance variable if it was defined
  # as a field.
  input.each do |n, v|
    if self.class.fields.key?(n)
      opts = self.class.fields[n]

      if (m = opts[:load])
        if m.is_a?(Symbol)
          v = BUILTIN_LOADERS[m].call(v)
        else
          v = m.call(v)
        end
      end

      if opts[:freeze]
        v = v.freeze
      end

      instance_variable_set(:"@#{opts[:as]}", v)
    end
  end
end

Public Instance Methods

==(other) click to toggle source
# File lib/nomad/response.rb, line 125
def ==(other)
  self.to_h == other.to_h
end
to_h() click to toggle source

Create a hash-bashed representation of this response.

@return [Hash]

# File lib/nomad/response.rb, line 112
def to_h
  self.class.fields.inject({}) do |h, (n, opts)|
    result = self.public_send(opts[:as])

    if !result.nil? && !result.is_a?(Array) && result.respond_to?(:to_h)
      result = result.to_h
    end

    h[opts[:as]] = result
    h
  end
end