Module: Recurly::Schema::ResourceCaster

Included in:
Request, Resource
Defined in:
lib/recurly/schema/resource_caster.rb

Overview

The purpose of this class is to turn JSON parsed Hashes defined into Recurly ruby objects. It's to be used by the Resource as an extension.

Instance Method Summary collapse

Instance Method Details

#cast(attributes = {}) ⇒ Resource

Gives the class the ability to initialize itself given some json data.

Examples:

Recurly::Resources::Account.cast({"code" => "mycode"})
#=> #<Recurly::Resources::Account @attributes={:code=>"mycode"}>

Parameters:

  • attributes (Hash) (defaults to: {})

    A primitive Hash from JSON.parse of Recurly response.

Returns:

  • (Resource)

    the Resource (ruby object) representing the passed in JSON data.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/recurly/schema/resource_caster.rb', line 19

def cast(attributes = {})
  resource = new()
  attributes.each do |attr_name, val|
    schema_attr = self.schema.get_attribute(attr_name)

    if schema_attr
      val = if val.nil?
          val
        elsif schema_attr.is_valid?(val)
          schema_attr.cast(val)
        else
          if Recurly::STRICT_MODE
            msg = "#{self.class}##{attr_name} does not have the right type. Value: #{val.inspect} was expected to be a #{schema_attr}"
            raise ArgumentError, msg
          end
        end

      writer = "#{attr_name}="
      resource.send(writer, val)
    elsif Recurly::STRICT_MODE
      raise ArgumentError, "#{resource.class.name} encountered json attribute #{attr_name.inspect}: #{val.inspect} but it's unknown to it's schema"
    end
  end
  resource
end