Add support for resource-level JSON API links.

This commit is contained in:
Lucas Hosseini
2015-10-06 19:35:09 +02:00
parent 827a623d16
commit 3804dcc238
4 changed files with 108 additions and 5 deletions

View File

@@ -5,6 +5,7 @@ module ActiveModel
extend ActiveSupport::Autoload
autoload :PaginationLinks
autoload :FragmentCache
autoload :Link
# TODO: if we like this abstraction and other API objects to it,
# then extract to its own file and require it.
@@ -94,7 +95,7 @@ module ActiveModel
if serializer.paginated?
hash[:links] ||= {}
hash[:links].update(links_for(serializer, options))
hash[:links].update(pagination_links_for(serializer, options))
end
hash
@@ -136,12 +137,21 @@ module ActiveModel
{ id: id.to_s, type: type }
end
def attributes_for(serializer, fields)
serializer.attributes(fields).except(:id)
end
def resource_object_for(serializer)
cache_check(serializer) do
resource_object = resource_identifier_for(serializer)
requested_fields = fieldset && fieldset.fields_for(resource_object[:type])
attributes = serializer.attributes(requested_fields).except(:id)
attributes = attributes_for(serializer, requested_fields)
resource_object[:attributes] = attributes if attributes.any?
links = links_for(serializer)
resource_object[:links] = links if links.any?
resource_object
end
end
@@ -204,7 +214,21 @@ module ActiveModel
end
end
def links_for(serializer, options)
def links_for(serializer)
serializer.links.each_with_object({}) do |(name, value), hash|
hash[name] =
if value.respond_to?(:call)
link = Link.new(serializer)
link.instance_eval(&value)
link.to_hash
else
value
end
end
end
def pagination_links_for(serializer, options)
JsonApi::PaginationLinks.new(serializer.object, options[:context]).serializable_hash(options)
end
end