Skip to content

Instantly share code, notes, and snippets.

@amolpujari
Last active April 18, 2020 06:58
Show Gist options
  • Save amolpujari/37dc624afea9d12ed2e0c807417a861d to your computer and use it in GitHub Desktop.
Save amolpujari/37dc624afea9d12ed2e0c807417a861d to your computer and use it in GitHub Desktop.
rails 5 fast_jsonapi oj serializer api action
# frozen_string_literal: true
module JsonResponse
extend ActiveSupport::Concern
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 !request.get? && resource.respond_to?(:errors) && resource.errors.any?
status = :bad_request
end
if resource.is_a?(Hash) || resource.is_a?(Array)
render json: resource, status: status
else
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
data = serializer_klass.new(resource).to_h
return data unless root
{ root => data }
end
end
# todos_controller.rb
# frozen_string_literal: true
class Api::V1::TodosController < Api::V1::ApplicationController
include JsonResponse
# .... some code here
api_action(:todo_ids){ @task.todo_ids }
api_action :index do
if parsed_validated_ids.present?
@todos = @task.todos.where(id: parsed_validated_ids)
else
@todos = @task.todos.page(page).per(per_page)
end
list
end
api_action(:show){ @todo }
api_action(:update){ @todo.update_attrs(update_params, current_user.id) }
.....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment