Add support for meta key

Test for meta_key serialization
This commit is contained in:
tchak 2012-10-13 00:55:55 +02:00
parent 6b88f1b6ef
commit a71698d5bb
3 changed files with 65 additions and 0 deletions

View File

@ -35,6 +35,14 @@ module ActiveModel
end end
end end
def meta_key
@options[:meta_key].try(:to_sym) || :meta
end
def include_meta(hash)
hash[meta_key] = @options[:meta] if @options.has_key?(:meta)
end
def as_json(*args) def as_json(*args)
@options[:hash] = hash = {} @options[:hash] = hash = {}
@options[:unique_values] = {} @options[:unique_values] = {}
@ -49,6 +57,8 @@ module ActiveModel
if root = @options[:root] if root = @options[:root]
hash.merge!(root => array) hash.merge!(root => array)
include_meta hash
hash
else else
array array
end end

View File

@ -227,6 +227,14 @@ module ActiveModel
@options[:url_options] || {} @options[:url_options] || {}
end end
def meta_key
@options[:meta_key].try(:to_sym) || :meta
end
def include_meta(hash)
hash[meta_key] = @options[:meta] if @options.has_key?(:meta)
end
# Returns a json representation of the serializable # Returns a json representation of the serializable
# object including the root. # object including the root.
def as_json(options={}) def as_json(options={})
@ -235,6 +243,7 @@ module ActiveModel
@options[:unique_values] = {} @options[:unique_values] = {}
hash.merge!(root => serializable_hash) hash.merge!(root => serializable_hash)
include_meta hash
hash hash
else else
serializable_hash serializable_hash

View File

@ -1186,4 +1186,50 @@ class SerializerTest < ActiveModel::TestCase
} }
}, actual) }, actual)
end end
def test_meta_key_serialization
tag_serializer = Class.new(ActiveModel::Serializer) do
attributes :name
end
tag_class = Class.new(Model) do
def name
@attributes[:name]
end
define_method :active_model_serializer do
tag_serializer
end
end
serializable_array = Class.new(Array)
array = serializable_array.new
array << tag_class.new(:name => 'Rails')
array << tag_class.new(:name => 'Sinatra')
actual = array.active_model_serializer.new(array, :root => :tags, :meta => {:total => 10}).as_json
assert_equal({
:meta => {
:total => 10,
},
:tags => [
{ :name => "Rails" },
{ :name => "Sinatra" },
]
}, actual)
actual = array.active_model_serializer.new(array, :root => :tags, :meta => {:total => 10}, :meta_key => 'meta_object').as_json
assert_equal({
:meta_object => {
:total => 10,
},
:tags => [
{ :name => "Rails" },
{ :name => "Sinatra" },
]
}, actual)
end
end end