Class: AdaptivePayments::Node

Inherits:
Virtus::Attribute
  • Object
show all
Defined in:
lib/pp-adaptive/support/node.rb

Overview

A Virtus Attribute used to box a type from the API to an Attribute in a JsonModel

The Node type should not be used directly. Instead it should be given a type to box.

attribute :child, Node[Child], :param => "childItem"

In the above, the model gets an Attribute named #child, mapping to a JSON parameter named ‘childItem’. The object at ‘model.child` is present by default, and is an object of type Child.

Assigning a Hash directly to the attribute will store an object of the boxed type, based on the elements in the Hash.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#typeObject (readonly)

Provide access to the boxed type



17
18
19
# File 'lib/pp-adaptive/support/node.rb', line 17

def type
  @type
end

Class Method Details

.[](type) ⇒ Node<type>

Returns a descendant of Node, boxing the given type

Parameters:

  • type (Class<JsonModel>)

    the class definition to box

Returns:

  • (Node<type>)

    an anonymous descendant of Node boxing the given type

Raises:

  • (ArgumentError)


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/pp-adaptive/support/node.rb', line 27

def [](type)
  raise ArgumentError, "Child nodes may only be other JsonModel classes" unless type <= JsonModel

  @generated_class_map       ||= {}
  @generated_class_map[type] ||= Class.new(self) do
    default lambda { |m, a| type.new }
    lazy true

    define_method :type do
      type
    end

    define_method :coerce do |value|
      value.kind_of?(Hash) ? type.new(value) : value
    end
  end
end