Class: Unimatrix::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/unimatrix/serializer.rb

Instance Method Summary collapse

Constructor Details

#initialize(payload = [], options = {}) ⇒ Serializer

Returns a new instance of Serializer.



5
6
7
8
# File 'lib/unimatrix/serializer.rb', line 5

def initialize( payload = [], options = {} )
  @payload = [ payload ].flatten
  @options = options
end

Instance Method Details

#serialize(node, options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/unimatrix/serializer.rb', line 10

def serialize( node, options = {} )
  result = {}
  result[ node ] = @payload.map do | object |
    node_object = {}
    node_object[ :type_name ] = (
      object.respond_to?( :type_name ) ?
        object.type_name :
        object.class.name.split( '::' ).last.underscore
    )
    if object.respond_to?( :fields )
      object.fields.each do | name, options |
        unless options[ :read_only ]
          value = object.send( name ) if object.respond_to?( name )
          if value.is_a?( Struct )
            nested_attributes = value.members
            nested_attributes.each do | nested_attribute |
              key = "#{ name }.#{ nested_attribute }"
              nested_attribute_value = value.send( nested_attribute )
              node_object[ key.to_sym ] = value.send( nested_attribute ) if value.send( nested_attribute )
            end
          else
            node_object[ name.to_sym ] = value
          end
        end
      end
    end
    node_object
  end
  result
end