Class: JSONAPI::ResourceSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi/resource_serializer.rb

Instance Method Summary collapse

Instance Method Details

#serialize_to_hash(source, options = {}) ⇒ Object

Converts a single resource, or an array of resources to a hash, conforming to the JSONAPI structure include:

Purpose: determines which objects will be side loaded with the source objects in a linked section
Example: ['comments','author','comments.tags','author.posts']

fields:

Purpose: determines which fields are serialized for a resource type. This encompasses both attributes and
         association ids in the links section for a resource. Fields are global for a resource type.
Example: { people: [:id, :email, :comments], posts: [:id, :title, :author], comments: [:id, :body, :post]}


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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/jsonapi/resource_serializer.rb', line 12

def serialize_to_hash(source, options = {})
  is_resource_collection = source.respond_to?(:to_ary)
  return {} if source.nil? || (is_resource_collection && source.size == 0)

  @fields =  options.fetch(:fields, {})
  include = options.fetch(:include, [])

  @key_formatter = options.fetch(:key_formatter, JSONAPI.configuration.key_formatter)

  @linked_objects = {}

  requested_associations = parse_includes(include)

  if is_resource_collection
    @primary_class_name = source[0].class._type
  else
    @primary_class_name = source.class._type
  end

  process_primary(source, requested_associations)

  primary_class_name = @primary_class_name.to_sym

  linked_hash = {}
  primary_objects = []
  @linked_objects.each do |class_name, objects|
    class_name = class_name.to_sym

    linked_objects = []
    objects.each_value do |object|
      if object[:primary]
        primary_objects.push(object[:object_hash])
      else
        linked_objects.push(object[:object_hash])
      end
    end
    linked_hash[format_key(class_name)] = linked_objects unless linked_objects.empty?
  end

  if is_resource_collection
    primary_hash = {format_key(primary_class_name) => primary_objects}
  else
    primary_hash = {format_key(primary_class_name) => primary_objects[0]}
  end

  if linked_hash.size > 0
    primary_hash.merge({linked: linked_hash})
  else
    primary_hash
  end
end