active_model_serializers/lib/active_model/serializer/adapter.rb
Alexandre de Oliveira bd27da1b76 Adds support for meta attribute
Currently, 0.10.0.pre doesn't support `meta` option in `render`. This
way, there's no way to support features such as pagination. `0.9` had
this feature in place.

This adds support for it, as well as fixes small things in README.md.

This won't support `meta` in array responses because arrays don't have
keys, obviously. Also, the response should have a `root` key, otherwise
no `meta` will be included.

In some cases, for example using JsonApi, ArraySerializer will result in
a response with a `root`. In that case, `meta` will be included.
2015-01-05 02:56:33 -02:00

56 lines
1.3 KiB
Ruby

module ActiveModel
class Serializer
class Adapter
extend ActiveSupport::Autoload
autoload :Json
autoload :Null
autoload :JsonApi
attr_reader :serializer
def initialize(serializer, options = {})
@serializer = serializer
@options = options
end
def serializable_hash(options = {})
raise NotImplementedError, 'This is an abstract method. Should be implemented at the concrete adapter.'
end
def as_json(options = {})
hash = serializable_hash(options)
include_meta(hash)
end
def self.create(resource, options = {})
override = options.delete(:adapter)
klass = override ? adapter_class(override) : ActiveModel::Serializer.adapter
klass.new(resource, options)
end
def self.adapter_class(adapter)
"ActiveModel::Serializer::Adapter::#{adapter.to_s.classify}".safe_constantize
end
private
def meta
serializer.meta if serializer.respond_to?(:meta)
end
def meta_key
serializer.meta_key || "meta"
end
def root
serializer.json_key
end
def include_meta(json)
json[meta_key] = meta if meta && root
json
end
end
end
end