mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
commit
6780cd3df5
@ -35,6 +35,14 @@ module ActiveModel
|
||||
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)
|
||||
@options[:hash] = hash = {}
|
||||
@options[:unique_values] = {}
|
||||
@ -49,6 +57,8 @@ module ActiveModel
|
||||
|
||||
if root = @options[:root]
|
||||
hash.merge!(root => array)
|
||||
include_meta hash
|
||||
hash
|
||||
else
|
||||
array
|
||||
end
|
||||
|
||||
@ -242,6 +242,14 @@ module ActiveModel
|
||||
@options[:url_options] || {}
|
||||
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
|
||||
# object including the root.
|
||||
def as_json(options={})
|
||||
@ -250,6 +258,7 @@ module ActiveModel
|
||||
@options[:unique_values] = {}
|
||||
|
||||
hash.merge!(root => serializable_hash)
|
||||
include_meta hash
|
||||
hash
|
||||
else
|
||||
serializable_hash
|
||||
|
||||
@ -1192,4 +1192,50 @@ class SerializerTest < ActiveModel::TestCase
|
||||
}
|
||||
}, actual)
|
||||
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
|
||||
|
||||
Loading…
Reference in New Issue
Block a user