Makes Grape::Endpoint quack like an ActionController

This commit is contained in:
John Allen 2013-05-15 21:42:02 -04:00
parent e5cf9bdf8c
commit f8aff8dff2

View file

@ -1,5 +1,14 @@
require 'active_record'
require 'pry'
# Make the Grape::Endpoint quiack like a controller
module Grape
class Endpoint
def default_serializer_options; end
def serialization_scope; end
def _serialization_scope; end
def url_options; end
end
end
module Grape
module Formatter
@ -18,7 +27,7 @@ module Grape
route_options = endpoint.options[:route_options]
options = namespace_options.merge(route_options)
serializer = serializer(endpoint, resource, options)
serializer = ::ActiveModel::Serializer.build_json(endpoint, resource, options)
if serializer
serializer.to_json
@ -26,34 +35,6 @@ module Grape
Grape::Formatter::Json.call resource, env
end
end
private
def serializer(endpoint, resource, options={})
serializer = options.delete(:serializer) ||
(resource.respond_to?(:active_model_serializer) &&
resource.active_model_serializer)
return serializer unless serializer
if resource.respond_to?(:to_ary)
unless serializer <= ActiveModel::ArraySerializer
raise ArgumentError.new("#{serializer.name} is not an ArraySerializer. " +
"You may want to use the :each_serializer option instead.")
end
if options[:root] != false && serializer.root != false
# the serializer for an Array is ActiveModel::ArraySerializer
options[:root] ||= serializer.root || resource.first.class.name.underscore.pluralize
end
end
# options[:scope] = controller.serialization_scope unless options.has_key?(:scope)
# options[:scope_name] = controller._serialization_scope
# options[:url_options] = controller.url_options
serializer.new(resource, options)
end
end
end
end