Class: JsonApiServer::BaseSerializer

Inherits:
Object
  • Object
show all
Includes:
ApiVersion, Serializer
Defined in:
lib/json_api_server/base_serializer.rb

Overview

Description

Base JSON API serializer for this gem. Based on spec document structure: http://jsonapi.org/format/#document-structure. Classes should inherit and override. ResourceSerializer and ResourcesSerializer inherit from this class.

Consists of 4 methods (#links, #data, #included, #meta) which create the following document structure. The 4 methods should return data that is serializable to JSON.

{
":jsonapi": {
 ":version": "1.0"
},
":links": null,
":data": null,
":included": null,
":meta": null
}

There is an additional method, #relationship_data, which should be populated with data for "relationships".

Example class:

class CommentSerializer < JsonApiServer::BaseSerializer
def initialize(object, **options)
  super(options)
  @object = object
end

def links
  {
    self: File.join(base_url, "/comments/#{@object.id}")
  }
end

def data
  {
    "type": "comments",
    "id": "12",
    "attributes": {
      "comment": @object.comment,
      "created_at": @object.created_at,
      "updated_at": @object.created_at,
    },
    "relationships": {
      "author": {
        "links": {"self": "http://example.com/people/#{@object.author_id}"},
        "data": {"id": @object.author_id, "type": "people"}
      }
    }
  }
end
end

Sometimes only part of document is needed, i.e., when embedding one serializer in another. as_json takes an optional hash argument which determines which parts of the document to return. These options can also be set in the #as_json_options attribute.

serializer.as_json(include: [:data]) # => { data: ... } serializer.as_json(include: [:links]) # => { links: ... } serializer.as_json(include: [:data, :links]) # =>

links: {...,

data: ...

}

serializer.as_json(include: [:relationship_data]) # =>

data: {

# usually links or object_id + type.

}

base_url -- is JsonApiServer::Configuration#base_url exposed as a protected method. For creating links.

Direct Known Subclasses

ResourceSerializer

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ApiVersion

#jsonapi

Methods included from Serializer

#serializer_options, #to_json

Constructor Details

#initialize(**options) ⇒ BaseSerializer

Returns a new instance of BaseSerializer.



103
104
105
# File 'lib/json_api_server/base_serializer.rb', line 103

def initialize(**options)
  @as_json_options = options[:as_json_options]
end

Instance Attribute Details

#as_json_optionsObject

Hash. as_json options. Same options can be passed into #as_json. Defaults to nil. When not set, all sections are rendered.

Possible options:

:include (Array) -- Optional. Possible values: :jsonapi, :links, :data, :included, :meta and :relationship_data. :relationship_data is a special case -- if present in the array, only relationship data is rendered (data section w/o attributes).

i.e,

# Set attribute
serializer.as_json_options = { include: [:data] }
serializer.as_json_options = { include: [:data, :links] }
serializer.as_json_options = { include: [:relationship_data] }

# Or set when calling #as_json
serializer.as_json(include: [:data])


101
102
103
# File 'lib/json_api_server/base_serializer.rb', line 101

def as_json_options
  @as_json_options
end

Instance Method Details

#as_json(**options) ⇒ Object

Creates the following document structure by default. See #as_json_options for a description of options. The hash is with indifferent access. { "jsonapi" => { "version" => "1.0" }, "links" => null, "data" => null, "included" => null, "meta" => null }



148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/json_api_server/base_serializer.rb', line 148

def as_json(**options)
  opts = (options.any? ? options : as_json_options) || {}
  sections = opts[:include] || %w[jsonapi links data included meta]
  hash = {}

  if sections.include?(:relationship_data)
    hash['data'] = relationship_data
  else
    sections.each { |s| hash[s] = send(s) if sections.include?(s) }
  end

  ActiveSupport::HashWithIndifferentAccess.new(hash)
end

#dataObject

JSON API data section. Subclass implements. Api spec: http://jsonapi.org/format/#document-structure



115
116
117
# File 'lib/json_api_server/base_serializer.rb', line 115

def data
  nil
end

#includedObject

JSON API included section. Sublclass implements. Api spec: http://jsonapi.org/format/#fetching-includes



127
128
129
# File 'lib/json_api_server/base_serializer.rb', line 127

def included
  nil
end

JSON API links section. Subclass implements. Api spec: http://jsonapi.org/format/#document-links



109
110
111
# File 'lib/json_api_server/base_serializer.rb', line 109

def links
  nil
end

#metaObject

JSON API meta section. Sublclass implements. Api spec: http://jsonapi.org/format/#document-meta



133
134
135
# File 'lib/json_api_server/base_serializer.rb', line 133

def meta
  nil
end

#relationship_dataObject

JSON to render with #as_json_option :relationship_data. Subclass implements. Api spec: http://jsonapi.org/format/#fetching-relationships



121
122
123
# File 'lib/json_api_server/base_serializer.rb', line 121

def relationship_data
  nil
end