Class: Anypost::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/anypost/response.rb

Overview

An immutable view over a decoded JSON response object.

Read fields with either method or bracket syntax — both return the same value, and nested objects come back as Response instances:

email = client.email.send(...)
email.id          # "email_..."
email[:id]        # same
email["id"]       # same

Lists of objects come back as plain Ruby arrays whose object elements are themselves Response instances. Call #to_h for the raw decoded hash.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Response

Returns a new instance of Response.

Parameters:

  • attributes (Hash)

    decoded JSON object (string keys)



27
28
29
# File 'lib/anypost/response.rb', line 27

def initialize(attributes)
  @attributes = attributes
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



58
59
60
61
62
63
64
65
# File 'lib/anypost/response.rb', line 58

def method_missing(name, *args)
  key = name.to_s
  if @attributes.key?(key)
    Response.wrap(@attributes[key])
  else
    super
  end
end

Class Method Details

.wrap(value) ⇒ Object

Wrap a decoded JSON value, turning object-shaped hashes into responses.



18
19
20
21
22
23
24
# File 'lib/anypost/response.rb', line 18

def self.wrap(value)
  case value
  when Hash then new(value)
  when Array then value.map { |element| wrap(element) }
  else value
  end
end

Instance Method Details

#==(other) ⇒ Object



46
47
48
# File 'lib/anypost/response.rb', line 46

def ==(other)
  other.is_a?(Response) ? to_h == other.to_h : @attributes == other
end

#[](key) ⇒ Object



31
32
33
# File 'lib/anypost/response.rb', line 31

def [](key)
  Response.wrap(@attributes[key.to_s])
end

#inspectObject



50
51
52
# File 'lib/anypost/response.rb', line 50

def inspect
  "#<Anypost::Response #{@attributes.inspect}>"
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/anypost/response.rb', line 35

def key?(key)
  @attributes.key?(key.to_s)
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/anypost/response.rb', line 54

def respond_to_missing?(name, include_private = false)
  @attributes.key?(name.to_s) || super
end

#to_hHash Also known as: to_hash

The raw decoded response, with no Anypost::Response wrapping at any depth.

Returns:

  • (Hash)


41
42
43
# File 'lib/anypost/response.rb', line 41

def to_h
  @attributes
end