Sha256: 5c865d303a16a028521c053aecc599cf3dea10e2d5e03ece3b1f0e695e7efed3

Contents?: true

Size: 1.12 KB

Versions: 11

Compression:

Stored size: 1.12 KB

Contents

# A Grape response formatter that can be used as 'formatter :json, Grape::Formatters::ActiveModelSerializers'
#
# Serializer options can be passed as a hash from your Grape endpoint using env[:active_model_serializer_options],
# or better yet user the render helper in Grape::Helpers::ActiveModelSerializers

require 'active_model_serializers/serialization_context'

module Grape
  module Formatters
    module ActiveModelSerializers
      def self.call(resource, env)
        serializer_options = build_serializer_options(env)
        ::ActiveModelSerializers::SerializableResource.new(resource, serializer_options).to_json
      end

      def self.build_serializer_options(env)
        ams_options = env[:active_model_serializer_options] || {}

        # Add serialization context
        ams_options.fetch(:serialization_context) do
          request = env['grape.request']
          ams_options[:serialization_context] = ::ActiveModelSerializers::SerializationContext.new(
            request_url: request.url[/\A[^?]+/],
            query_parameters: request.params
          )
        end

        ams_options
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
active_model_serializers-0.10.8 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.7 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.6 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.5 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.4 lib/grape/formatters/active_model_serializers.rb
agi_active_model_serializers-0.10.9 lib/grape/formatters/active_model_serializers.rb
agi_active_model_serializers-0.10.8 lib/grape/formatters/active_model_serializers.rb
agi_active_model_serializers-0.10.7 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.3 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.2 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.1 lib/grape/formatters/active_model_serializers.rb