Last active
April 18, 2020 06:58
-
-
Save amolpujari/6404e2784ec5289fb38816235238038f to your computer and use it in GitHub Desktop.
rails 5 fast_jsonapi oj serializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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