Last active
September 4, 2015 17:45
-
-
Save tiagopog/4bea8ee01c73d8e32ab4 to your computer and use it in GitHub Desktop.
JSON API - Helper methods for controllers
This file contains hidden or 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
module JsonapiUtils | |
extend ActiveSupport::Concern | |
include do | |
helper_method :jsonapi_serialize, :jsonapi_serialize_collection | |
end | |
def jsonapi_serialize_collection(records) | |
records = records.map { |record| @request.resource_klass.new(record) } | |
jsonapi_serialize(records) | |
end | |
def jsonapi_serialize(records) | |
is_collection = records.is_a?(Array) | |
resources = is_collection ? records : @request.resource_klass.new(records) | |
@included = params[:include].present? ? params[:include].split(',') : [] | |
@resources = | |
JSONAPI::ResourceSerializer.new( | |
@request.resource_klass, | |
include: @included, | |
fields: @request.fields | |
).serialize_to_hash(resources) | |
if is_collection | |
@resources.merge({ | |
meta: { | |
record_count: records.size.zero? ? 0 : records.first.model.class.count | |
} | |
}) | |
else | |
@resources | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment