Method: JSONAPI::ResourceSerializer#serialize_to_hash

Defined in:
lib/jsonapi/resource_serializer.rb

#serialize_to_hash(source) ⇒ Object

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



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/jsonapi/resource_serializer.rb', line 39

def serialize_to_hash(source)
  @top_level_sources = Set.new([source].flatten.compact.map {|s| top_level_source_key(s) })

  is_resource_collection = source.respond_to?(:to_ary)

  @included_objects = {}
  @include_directives ||= JSONAPI::IncludeDirectives.new(@primary_resource_klass, @include)

  process_primary(source, @include_directives.include_directives)

  included_objects = []
  primary_objects = []
  @included_objects.each_value do |objects|
    objects.each_value do |object|
      if object[:primary]
        primary_objects.push(object[:object_hash])
      else
        included_objects.push(object[:object_hash])
      end
    end
  end

  primary_hash = { data: is_resource_collection ? primary_objects : primary_objects[0] }

  primary_hash[:included] = included_objects if included_objects.size > 0
  primary_hash
end