mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Merge pull request #1336 from johnhamelink/master
Grape formatter feature requested in #1258 - Rebased and Repushed (#1273)
This commit is contained in:
14
lib/grape/active_model_serializers.rb
Normal file
14
lib/grape/active_model_serializers.rb
Normal 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
|
||||
15
lib/grape/formatters/active_model_serializers.rb
Normal file
15
lib/grape/formatters/active_model_serializers.rb
Normal 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
|
||||
16
lib/grape/helpers/active_model_serializers.rb
Normal file
16
lib/grape/helpers/active_model_serializers.rb
Normal 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
|
||||
Reference in New Issue
Block a user