Class: Dato::JsonApiDeserializer

Inherits:
Object
  • Object
show all
Defined in:
lib/dato/json_api_deserializer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema) ⇒ JsonApiDeserializer

Returns a new instance of JsonApiDeserializer.



9
10
11
# File 'lib/dato/json_api_deserializer.rb', line 9

def initialize(schema)
  @schema = schema
end

Instance Attribute Details

#schemaObject (readonly)

Returns the value of attribute schema.



7
8
9
# File 'lib/dato/json_api_deserializer.rb', line 7

def schema
  @schema
end

Instance Method Details

#deserialize(data) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/dato/json_api_deserializer.rb', line 13

def deserialize(data)
  return nil unless data

  data = data[:data]

  if data.is_a? Array
    data.map { |resource| deserialize_resource(resource) }
  else
    deserialize_resource(data)
  end
end

#deserialize_resource(data) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/dato/json_api_deserializer.rb', line 25

def deserialize_resource(data)
  result = { id: data[:id] }
  result[:meta] = data[:meta] if data[:meta]
  result.merge!(data[:attributes]) if data[:attributes]

  if data[:relationships]
    relationships.each do |relationship, meta|
      next unless data[:relationships][relationship]

      rel_data = data[:relationships][relationship][:data]

      result[relationship] = if meta[:types].length > 1
                               rel_data
                             elsif !rel_data
                               nil
                             elsif meta[:collection]
                               rel_data.map { |ref| ref[:id] }
                             else
                               rel_data[:id]
                             end
    end
  end

  result.with_indifferent_access
end

#relationshipsObject



51
52
53
# File 'lib/dato/json_api_deserializer.rb', line 51

def relationships
  @relationships ||= JsonSchemaRelationships.new(schema).relationships
end