Skip to content

Commit

Permalink
Fix rails-api#1759, Grape integration, adds serialization_context
Browse files Browse the repository at this point in the history
- `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`).
  • Loading branch information
onomated committed Jun 1, 2016
1 parent 159c529 commit 4dd9a3c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
20 changes: 18 additions & 2 deletions lib/grape/formatters/active_model_serializers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 0 additions & 6 deletions lib/grape/helpers/active_model_serializers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4dd9a3c

Please sign in to comment.