Sha256: 117004d79755184ce73267b9ec0c58beb5ed2ce1cf31e366136f5c2a80592e84

Contents?: true

Size: 1.15 KB

Versions: 8

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

# 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

8 entries across 8 versions & 2 rubygems

Version Path
active_model_serializers-0.10.15 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.14 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.13 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.12 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.11 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.10 lib/grape/formatters/active_model_serializers.rb
active_model_serializers_custom-0.10.90 lib/grape/formatters/active_model_serializers.rb
active_model_serializers-0.10.9 lib/grape/formatters/active_model_serializers.rb