From 4dd9a3c4cc88db0868bd16c493bfa4535be817d4 Mon Sep 17 00:00:00 2001 From: Onome Date: Wed, 1 Jun 2016 18:26:26 -0500 Subject: [PATCH] Fix #1759, Grape integration, adds serialization_context - `serialization_context` is added in grape formatter so grape continues to render models without an explicit call to the `render` helper method - Made it straightforward for subclasses to add other serializer options (such as `serialization_scope`). --- .../formatters/active_model_serializers.rb | 20 +++++++++++++++++-- lib/grape/helpers/active_model_serializers.rb | 6 ------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/lib/grape/formatters/active_model_serializers.rb b/lib/grape/formatters/active_model_serializers.rb index 20537e74f..10a1755a6 100644 --- a/lib/grape/formatters/active_model_serializers.rb +++ b/lib/grape/formatters/active_model_serializers.rb @@ -6,10 +6,26 @@ module Grape module Formatters module ActiveModelSerializers def self.call(resource, env) - serializer_options = {} - serializer_options.merge!(env[:active_model_serializer_options]) if env[:active_model_serializer_options] + serializer_options = build_serializer_options(env) ::ActiveModelSerializers::SerializableResource.new(resource, serializer_options).to_json end + + protected + + 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 diff --git a/lib/grape/helpers/active_model_serializers.rb b/lib/grape/helpers/active_model_serializers.rb index baaa166d8..484e03181 100644 --- a/lib/grape/helpers/active_model_serializers.rb +++ b/lib/grape/helpers/active_model_serializers.rb @@ -11,12 +11,6 @@ module ActiveModelSerializers # # Example: To include pagination meta data: render(posts, meta: { page: posts.page, total_pages: posts.total_pages }) def render(resource, active_model_serializer_options = {}) - active_model_serializer_options.fetch(:serialization_context) do - active_model_serializer_options[:serialization_context] = ::ActiveModelSerializers::SerializationContext.new( - original_url: request.url[/\A[^?]+/], - query_parameters: request.params - ) - end env[:active_model_serializer_options] = active_model_serializer_options resource end