Add ArraySerializer's root and meta features

This commit is contained in:
Santiago Pastorino
2013-08-23 19:17:17 -03:00
parent 70ea6c6bc7
commit a820e9774f
4 changed files with 176 additions and 4 deletions

View File

@@ -1,10 +1,23 @@
module ActiveModel
class ArraySerializer
def initialize(object, options={})
@object = object
@options = options
class << self
attr_accessor :_root
def root(root)
@_root = root
end
alias root= root
end
def initialize(object, options={})
@object = object
@options = options
@root = options[:root] || self.class._root
@meta_key = options[:meta_key] || :meta
@meta = options[@meta_key]
end
attr_accessor :object, :root, :meta_key, :meta
def serializable_array
@object.map do |item|
serializer = @options[:each_serializer] || Serializer.serializer_for(item)
@@ -16,5 +29,15 @@ module ActiveModel
end
end
alias serializable_object serializable_array
def as_json(options={})
if root = options[:root] || self.root
hash = { root.to_s => serializable_array }
hash[meta_key.to_s] = meta if meta
hash
else
serializable_array
end
end
end
end