Class: JsonApiServer::ResourceSerializer

Inherits:
BaseSerializer show all
Defined in:
lib/json_api_server/resource_serializer.rb

Overview

Description

Serializer class for a resource. Subclasses JsonApiServer::BaseSerializer.

Example class:

class CommentSerializer < JsonApiServer::ResourceSerializer
  resource_type 'comments'

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

  def data
    {}.tap do |h|
      h['type'] = self.class.type
      h['id'] = @object.id
      h['attributes'] = attributes
      h['relationships'] = inclusions.relationships if inclusions?
    end
  end

  def included
    inclusions.included if inclusions?
  end

  protected

  def attributes
    attributes_builder
      .add_multi(@object, 'title', 'comment')
      .add('created_at', @object.created_at.try(:iso8601, 9))
      .add('updated_at', @object.updated_at.try(:iso8601, 9))
      .attributes
  end

  def inclusions
    @inclusions ||= begin
      if relationship?('comment.author')
        relationships_builder.relate('author', user_serializer(@object.author))
      end
      if relationship?('comment.author.links')
        relationships_builder.include('author', user_serializer(@object.author),
                                      relate: { include: [:links] })
      end
      relationships_builder
    end
  end

  def user_serializer(user, as_json_options = { include: [:data] })
    ::UserSerializer.new(
      user,
      includes: includes,
      fields: fields,
      as_json_options: as_json_options
    )
  end
end

Create an instance from builder:

builder = JsonApiServer::Builder.new(request, Comment.find(params[:id]))
  .add_include(['comment.author', 'comment.author.links'])
  .add_fields

serializer = CommentSerializer.from_builder(builder)

Direct Known Subclasses

ResourcesSerializer

Instance Attribute Summary collapse

Attributes inherited from BaseSerializer

#as_json_options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseSerializer

#as_json, #data, #included, #links, #meta

Methods included from ApiVersion

#jsonapi

Methods included from Serializer

#as_json, #serializer_options, #to_json

Constructor Details

#initialize(object, **options) ⇒ ResourceSerializer

  • object - instance of model or presenter or whatever stores data.

  • options - Hash (optional):

    • :includes - Instance of JsonApiServer::Include or nil. Sets #includes.

    • :fields - Instance of JsonApiServer::Fields or nil. Sets #fields.



96
97
98
99
100
101
# File 'lib/json_api_server/resource_serializer.rb', line 96

def initialize(object, **options)
  super(options)
  @object = object
  @includes = options[:includes]
  @fields = options[:fields]
end

Instance Attribute Details

#fieldsObject (readonly)

Hash. Fields requested by user. From the ‘fields’ param. Extracted via JsonApiServer::Fields#sparse_fields which is also available through JsonApiServer::Builder#sparse_fields. Defaults to nil. Set in initializer options.

i.e.,

GET /articles?include=author&fields[articles]=title,body&fields[people]=name becomes:
fields = {'articles' => ['title', 'body'], 'people' => ['name']}


90
91
92
# File 'lib/json_api_server/resource_serializer.rb', line 90

def fields
  @fields
end

#includesObject (readonly)

Array. Relationships to include. Array of strings. From the ‘include’ param. Extracted via JsonApiServer::Include#includes which is also available through JsonApiServer::Builder#includes. Defaults to nil. Set in initializer options.

i.e.,

GET /articles?include=comments.author,publisher becomes:
includes = ['comments.author', 'publisher']


79
80
81
# File 'lib/json_api_server/resource_serializer.rb', line 79

def includes
  @includes
end

Class Method Details

.from_builder(builder, **options) ⇒ Object

  • :builder - Instance of JsonApiServer::Builder.

#object, #includes and #fields will be extracted from it.

  • options - Hash, override values from Builder or set additional options.

    • :includes - Instance of JsonApiServer::Include or nil. Sets #includes.

    • :fields - Instance of JsonApiServer::Fields or nil. Sets #fields.

    • filter - Instance of JsonApiServer::Filter or nil. Sets #filter.

    • :paginator - Instance of JsonApiServer::Fields or nil. Sets #paginator.

    • :as_json_options - See options at JsonApiServer::BaseSerializer#as_json_options.



124
125
126
127
128
129
130
# File 'lib/json_api_server/resource_serializer.rb', line 124

def from_builder(builder, **options)
  opts = options.merge(fields: options[:fields] || builder.sparse_fields,
                       includes: options[:includes] || builder.includes,
                       paginator: options[:paginator] || builder.paginator,
                       filter: options[:filter] || builder.filter)
  new(builder.query, opts)
end

.resource_type(type) ⇒ Object

‘type’ used in #relationship_data.



112
113
114
# File 'lib/json_api_server/resource_serializer.rb', line 112

def resource_type(type)
  @type = type
end

.typeObject

‘type’ used in #relationship_data and #data. i.e.:

"data": {"type": "articles", "id": 2}


107
108
109
# File 'lib/json_api_server/resource_serializer.rb', line 107

def type
  @type || type_from_class_name
end

Instance Method Details

#relationship_dataObject

Content when #as_json_options [:relationship_data] is specified. Defaults to { ‘type’ => <resource_type>, ‘id’ => <@object.id> }. resource_type can be set with class method #resource_type, otherwise it will be guessed from serializer class name.



149
150
151
152
# File 'lib/json_api_server/resource_serializer.rb', line 149

def relationship_data
  id = @object.try(:id) || @object.try(:[], :id)
  { 'type' => self.class.type, 'id' => id }
end