1

I have the following method in an API controller:

module Api
  module V1
    class ArticlesController < Api::BaseController

      def show
        article = Article.find(params[:id])
        render json: article
      end

end end end

And while using the active_model_serializers gem, I have the following serializer:

class Api::V1::ArticleSerializer < ActiveModel::Serializer
  attributes :id, :author_id, :title, :description
end

For all API requests the server should include information about the session, such as the api token and the current user. So in the above case the generated json shouldn't only include the attributes mentioned in the articles serializer but also for example the api token.

Where and how does one normally include this session information to send to the API front end? Is this perhaps in a separate serializer that is included in addition to in this case the articles serializer?

Marty
  • 2,132
  • 4
  • 21
  • 47

1 Answers1

1

Since you want this information attached to all API responses, it makes sense to have a superclass serializer responsible for this, which all other serializers inherit from:

class SerializerWithSessionMetadata < ActiveModel::Serializer
  attributes :token, :user

  def token
    # ...
  end

  def user
    # ...
  end
end

Then your serializers would inherit from this instead of ActiveModel::Serializer:

class ArticleSerializer < SerializerWithSessionMetadata
  # ...
end

Alternatively, you could make it a module that you include in your serializers:

module SessionMetadataSerializer
  def self.included(klass)
    klass.attributes :token, :user
  end

  def token
    # ...
  end

  # ...
end

Then:

class Api::V1::ArticleSerializer < ActiveModel::Serializer
  include SessionMetadataSerializer
  attributes :id, :author_id, :title, :description
end
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • Thanks @Jordan. For the token, would it be sufficient to define `@token` in the controller method that calls on a serializer, and then in the superclass serializer set: `def token` ; `@token` `end` ? Is that the way to do that? – Marty Jan 22 '16 at 15:12
  • 1
    No, serializers don't have access to a controller's instance variables. What version of active_model_serializers are you using? It looks like `serialization_options` is the way to go in 0.9.4, as described in this answer: http://stackoverflow.com/a/26780514 – Jordan Running Jan 22 '16 at 16:33