Class: Recurly::JSONParser

Inherits:
Object
  • Object
show all
Defined in:
lib/recurly/schema/json_parser.rb

Overview

This is a wrapper class to help parse http response into Recurly objects.

Class Method Summary collapse

Class Method Details

.from_json(data) ⇒ Error, Resource

Converts the parsed JSON into a Recurly object.

TODO: Instead of inferring this type from the `object` attribute. We should instead “register” the response type in the client/operations code. The `get`, `post`, etc methods could explicitly state their response types.

Parameters:

  • data (Hash)

    The parsed JSON data

Returns:



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/recurly/schema/json_parser.rb', line 28

def self.from_json(data)
  type = if data.has_key?("error")
      "error_may_have_transaction"
    else
      data["object"]
    end
  klazz = self.recurly_class(type)

  unless klazz
    raise ArgumentError, "Unknown resource for json type #{type}"
  end

  data = data["error"] if klazz == Resources::ErrorMayHaveTransaction

  klazz.cast(data)
end

.parse(client, body) ⇒ Resource

Parses the json body into a recurly object.

Parameters:

  • client (Client)

    The Recurly client which made the request.

  • body (String)

    The JSON string to parse.

Returns:



12
13
14
15
16
17
# File 'lib/recurly/schema/json_parser.rb', line 12

def self.parse(client, body)
  data = JSON.parse(body)
  from_json(data).tap do |object|
    object.client = client if object.requires_client?
  end
end

.recurly_class(type) ⇒ Resource, ...

Returns the Recurly ruby class responsible for the Recurly json key.

Examples:

JSONParser.recurly_class('list')
#=> Recurly::Page
JSONParser.recurly_class('shipping_address')
#=> Recurly::Resources::ShippingAddress

Parameters:

  • type (String)

    The JSON key.

Returns:



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/recurly/schema/json_parser.rb', line 56

def self.recurly_class(type)
  case type
  when nil
    nil
  when "list"
    Resources::Page
  else
    type_camelized = type.split("_").map(&:capitalize).join
    if Resources.const_defined?(type_camelized, false)
      Resources.const_get(type_camelized, false)
    elsif Recurly::STRICT_MODE
      raise ArgumentError, "Could not find Recurly Resource responsible for key #{type}"
    end
  end
end