Class: JsonApi::CollectionSerializer

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

Instance Method Summary collapse

Constructor Details

#initialize(objects, options = {}) ⇒ CollectionSerializer

Returns a new instance of CollectionSerializer.



58
59
60
61
62
63
# File 'lib/json_api_ruby/serializer.rb', line 58

def initialize(objects, options = {})
  @meta           = options.fetch('meta', Hash.new).stringify_keys
  @objects        = objects
  @includes       = options.fetch('include', [])
  @resource_class = options.fetch('resource_class', nil)
end

Instance Method Details

#assemble_included_data(relationships) ⇒ Object



92
93
94
95
96
97
# File 'lib/json_api_ruby/serializer.rb', line 92

def assemble_included_data(relationships)
  relationships.flat_map do |relationship|
    next if relationship.resources.blank?
    relationship.resources.map(&:to_hash)
  end.compact
end

#to_hashObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/json_api_ruby/serializer.rb', line 65

def to_hash
  serialized = {}
  included_data = []

  data_array = @objects.map do |object|
    resource_name  = "#{object.class.to_s.underscore}_resource".classify
    klass_name     = @resource_class || resource_name
    resource_klass = Resources::Discovery.resource_for_name(object, resource_class: klass_name)
    resource       = resource_klass.new(object, include: @includes)
    included_data += assemble_included_data(resource.relationships)
    resource.to_hash
  end

  serialized['data'] = data_array

  serialized['meta'] = @meta if @meta

  if included_data.present?
    included_data.uniq! do |inc_data|
      inc_data['id'] + inc_data['type']
    end
    serialized['included'] = included_data
  end

  serialized
end