Class: JSONAPI::ResourceSerializer
- Inherits:
-
Object
- Object
- JSONAPI::ResourceSerializer
- Defined in:
- lib/jsonapi/resource_serializer.rb
Instance Method Summary collapse
-
#initialize(primary_resource_klass) ⇒ ResourceSerializer
constructor
A new instance of ResourceSerializer.
-
#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.
Constructor Details
#initialize(primary_resource_klass) ⇒ ResourceSerializer
Returns a new instance of ResourceSerializer.
4 5 6 7 |
# File 'lib/jsonapi/resource_serializer.rb', line 4 def initialize(primary_resource_klass) @primary_resource_klass = primary_resource_klass @primary_class_name = @primary_resource_klass._type end |
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]}
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 |
# File 'lib/jsonapi/resource_serializer.rb', line 17 def serialize_to_hash(source, = {}) is_resource_collection = source.respond_to?(:to_ary) @fields = .fetch(:fields, {}) include = .fetch(:include, []) @key_formatter = .fetch(:key_formatter, JSONAPI.configuration.key_formatter) @linked_objects = {} requested_associations = parse_includes(include) process_primary(source, requested_associations) 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 |