Class: JSONAPI::ResourceSerializer

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

Instance Method Summary collapse

Instance Method Details

#serialize(source, include = [], fields = {}, context = nil) ⇒ Object

Serializes a single resource, or an array of resources 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
# File 'lib/jsonapi/resource_serializer.rb', line 12

def serialize(source, include = [], fields = {}, context = nil)
  @fields = fields
  @context = context
  @linked_objects = {}

  requested_associations = parse_includes(include)

  if source.respond_to?(:to_ary)
    return {} if source.size == 0
    @primary_class_name = source[0].class._serialize_as
  else
    @primary_class_name = source.class._serialize_as
  end

  process_primary(source, requested_associations)

  primary_class_name = @primary_class_name.to_sym
  primary_hash = {primary_class_name => []}

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

    linked = []
    objects.each_value do |object|
      if object[:primary]
        primary_hash[primary_class_name].push(object[:object_hash])
      else
        linked.push(object[:object_hash])
      end
    end
    linked_hash[class_name] = linked unless linked.empty?
  end

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

  return primary_hash
end