Skip to content

Instantly share code, notes, and snippets.

@amolpujari
Last active April 18, 2020 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amolpujari/6404e2784ec5289fb38816235238038f to your computer and use it in GitHub Desktop.
Save amolpujari/6404e2784ec5289fb38816235238038f to your computer and use it in GitHub Desktop.
rails 5 fast_jsonapi oj serializer
# frozen_string_literal: true
require 'time_difference'
module JsonResponse
extend ActiveSupport::Concern
LOGGER = Logger.new("#{Rails.root}/log/fast_jsonapi.log")
included do
end
module ClassMethods
def api_action action_name, &block
define_method action_name do
json_response block.call
end
end
end
def json_response(resource, root = nil, status = :ok)
if resource.is_a?(Hash) || resource.is_a?(Array)
render json: resource, status: status
else
if !request.get? && resource.respond_to?(:errors) && resource.errors.any?
status = :bad_request
end
render json: fast_json_for(resource, root), status: status
end
end
def fast_json_for(resource, root=nil)
serializer_klass = "#{controller_name.classify}Serializer".constantize
t1 = Time.now
data = serializer_klass.new(resource).to_h
t2 = Time.now
taken = "% 10.2f" % TimeDifference.between(t1, t2).in_ms
klass_name = "% 20s" % controller_name.classify
::JsonResponse::LOGGER.info "|#{klass_name}|#{taken}|"
return data unless root
{ root => data }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment