Skip to content

Instantly share code, notes, and snippets.

@EmCousin
Created February 21, 2018 19:00
Show Gist options
  • Save EmCousin/9a648c0effc669c7e6d9a41b3f42b98e to your computer and use it in GitHub Desktop.
Save EmCousin/9a648c0effc669c7e6d9a41b3f42b98e to your computer and use it in GitHub Desktop.
fast_jsonapi formatter for Grape
module Grape
module Formatter
module FastJsonapi
class << self
def call(object, _env)
return object if object.is_a?(String)
return ::Grape::Json.dump(serialize(object)) if serializable?(object)
return object.to_json if object.respond_to?(:to_json)
::Grape::Json.dump(object)
end
private
def serializable?(object)
object.respond_to?(:serializable_hash) || object.respond_to?(:to_a) && object.all? { |o| o.respond_to? :serializable_hash } || object.is_a?(Hash)
end
def serialize(object)
if object.respond_to? :serializable_hash
serializable_object(object).serializable_hash
elsif object.respond_to?(:to_a) && object.all? { |o| o.respond_to? :serializable_hash }
fast_jsonapi_serializable(object).serializable_hash || object.map(&:serializable_hash)
elsif object.is_a?(Hash)
h = {}
object.each_pair do |k, v|
h[k] = serialize(v)
end
h
else
object
end
end
def serializable_object(object)
fast_jsonapi_serializable(object) || object
end
def fast_jsonapi_serializable(object)
serializable_class(object)&.new(object)
end
def serializable_class(object)
(object.model_name.name + 'Serializer').safe_constantize
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment