mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
Merge pull request #69 from teeparham/array-serializer
Array serializer should support Hash, AMS, and PORO
This commit is contained in:
commit
8376a4dcd1
@ -52,7 +52,15 @@ module ActiveModel
|
|||||||
@options[:hash] = hash = {}
|
@options[:hash] = hash = {}
|
||||||
@options[:unique_values] = {}
|
@options[:unique_values] = {}
|
||||||
|
|
||||||
array = serializable_array.map(&:serializable_hash)
|
array = serializable_array.map do |item|
|
||||||
|
if item.is_a?(Hash)
|
||||||
|
item
|
||||||
|
elsif item.respond_to?(:serializable_hash)
|
||||||
|
item.serializable_hash
|
||||||
|
else
|
||||||
|
item.as_json
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
if root = @options[:root]
|
if root = @options[:root]
|
||||||
hash.merge!(root => array)
|
hash.merge!(root => array)
|
||||||
|
|||||||
@ -375,17 +375,18 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
}, serializer.as_json)
|
}, serializer.as_json)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# serialize different typed objects
|
||||||
def test_array_serializer
|
def test_array_serializer
|
||||||
model = Model.new
|
model = Model.new
|
||||||
user = User.new
|
user = User.new
|
||||||
comments = Comment.new(:title => "Comment1", :id => 1)
|
comments = Comment.new(:title => "Comment1", :id => 1)
|
||||||
|
|
||||||
array = [model, user, comments]
|
array = [model, user, comments]
|
||||||
serializer = array.active_model_serializer.new(array, {:scope => true})
|
serializer = array.active_model_serializer.new(array, :scope => {:scope => true})
|
||||||
assert_equal([
|
assert_equal([
|
||||||
{ :model => "Model" },
|
{ :model => "Model" },
|
||||||
{ :user => { :last_name=> "Valim", :ok => true, :first_name => "Jose", :scope => true } },
|
{ :last_name => "Valim", :ok => true, :first_name => "Jose", :scope => true },
|
||||||
{ :comment => { :title => "Comment1" } }
|
{ :title => "Comment1" }
|
||||||
], serializer.as_json)
|
], serializer.as_json)
|
||||||
end
|
end
|
||||||
|
|
||||||
@ -403,6 +404,13 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
]}, serializer.as_json)
|
]}, serializer.as_json)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_array_serializer_with_hash
|
||||||
|
hash = {:value => "something"}
|
||||||
|
array = [hash]
|
||||||
|
serializer = array.active_model_serializer.new(array, :root => :items)
|
||||||
|
assert_equal({ :items => [ hash ]}, serializer.as_json)
|
||||||
|
end
|
||||||
|
|
||||||
class CustomBlog < Blog
|
class CustomBlog < Blog
|
||||||
attr_accessor :public_posts, :public_user
|
attr_accessor :public_posts, :public_user
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user