Class: JsonApi::CollectionSerializer
- Inherits:
-
Object
- Object
- JsonApi::CollectionSerializer
- Defined in:
- lib/json_api_ruby/serializer.rb
Instance Method Summary collapse
- #assemble_included_data(included_resources) ⇒ Object
-
#initialize(objects, options = {}) ⇒ CollectionSerializer
constructor
A new instance of CollectionSerializer.
- #to_hash ⇒ Object
Constructor Details
#initialize(objects, options = {}) ⇒ CollectionSerializer
Returns a new instance of CollectionSerializer.
62 63 64 65 66 67 |
# File 'lib/json_api_ruby/serializer.rb', line 62 def initialize(objects, = {}) = .fetch('meta', Hash.new).stringify_keys @objects = objects @includes = .fetch('include', []) @resource_class = .fetch('resource_class', nil) end |
Instance Method Details
#assemble_included_data(included_resources) ⇒ Object
95 96 97 |
# File 'lib/json_api_ruby/serializer.rb', line 95 def assemble_included_data(included_resources) included_resources.map(&:to_hash) end |
#to_hash ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/json_api_ruby/serializer.rb', line 69 def to_hash serialized = {} included_resources = [] 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_resources += resource.relationships.select {|rel| rel.included?}.flat_map {|rel| rel.resources } resource.to_hash end included_resources.uniq! do |rel| rel.id + rel.type end serialized['data'] = data_array serialized['meta'] = if .present? serialized['included'] = assemble_included_data(included_resources) if included_resources.present? serialized end |