Merge pull request #1336 from johnhamelink/master

Grape formatter feature requested in #1258 - Rebased and Repushed (#1273)
This commit is contained in:
Benjamin Fleischer
2015-12-17 20:31:38 -06:00
8 changed files with 156 additions and 1 deletions

View File

@@ -0,0 +1,14 @@
# To add Grape support, require 'grape/active_model_serializers' in the base of your Grape endpoints
# Then add 'include Grape::ActiveModelSerializers' to enable the formatter and helpers
require 'active_model_serializers'
require 'grape/formatters/active_model_serializers'
require 'grape/helpers/active_model_serializers'
module Grape::ActiveModelSerializers
extend ActiveSupport::Concern
included do
formatter :json, Grape::Formatters::ActiveModelSerializers
helpers Grape::Helpers::ActiveModelSerializers
end
end

View File

@@ -0,0 +1,15 @@
# 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
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]
ActiveModel::SerializableResource.new(resource, serializer_options).to_json
end
end
end
end

View File

@@ -0,0 +1,16 @@
# Helpers can be included in your Grape endpoint as: helpers Grape::Helpers::ActiveModelSerializers
module Grape
module Helpers
module ActiveModelSerializers
# A convenience method for passing ActiveModelSerializers serializer options
#
# Example: To include relationships in the response: render(post, include: ['comments'])
#
# Example: To include pagination meta data: render(posts, meta: { page: posts.page, total_pages: posts.total_pages })
def render(resource, active_model_serializer_options = {})
env[:active_model_serializer_options] = active_model_serializer_options
resource
end
end
end
end