Class: JSONAPI::ResourceSerializer

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

Instance Method Summary collapse

Constructor Details

#initialize(primary_resource_klass, options = {}) ⇒ ResourceSerializer

Options can include 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]}

key_formatter: KeyFormatter class to override the default configuration base_url: a string to prepend to generated resource links



15
16
17
18
19
20
21
22
23
24
# File 'lib/jsonapi/resource_serializer.rb', line 15

def initialize(primary_resource_klass, options = {})
  @primary_resource_klass = primary_resource_klass
  @primary_class_name = @primary_resource_klass._type

  @fields =  options.fetch(:fields, {})
  @include = options.fetch(:include, [])
  @key_formatter = options.fetch(:key_formatter, JSONAPI.configuration.key_formatter)
  @route_formatter = options.fetch(:route_formatter, JSONAPI.configuration.route_formatter)
  @base_url = options.fetch(:base_url, '')
end

Instance Method Details

#serialize_to_hash(source) ⇒ Object

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



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
# File 'lib/jsonapi/resource_serializer.rb', line 27

def serialize_to_hash(source)
  is_resource_collection = source.respond_to?(:to_ary)

  @linked_objects = {}

  requested_associations = parse_includes(@include)

  process_primary(source, requested_associations)

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

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

  if linked_objects.size > 0
    primary_hash[:linked] = linked_objects
  else
    primary_hash
  end
  primary_hash
end


58
59
60
# File 'lib/jsonapi/resource_serializer.rb', line 58

def serialize_to_links_hash(source, requested_association)
  {data: link_object(source, requested_association, true)}
end