Support customer array serializer

This commit is contained in:
Tema Bolshakov 2014-08-18 12:34:03 +04:00 committed by Tema Bolshakov
parent be6ff586a2
commit c389ae2207
2 changed files with 28 additions and 3 deletions

View File

@ -58,7 +58,11 @@ end
if RUBY_VERSION >= '2.0' if RUBY_VERSION >= '2.0'
def serializer_for(resource) def serializer_for(resource)
if resource.respond_to?(:to_ary) if resource.respond_to?(:to_ary)
ArraySerializer if Object.constants.include?(:ArraySerializer)
::ArraySerializer
else
ArraySerializer
end
else else
begin begin
Object.const_get "#{resource.class.name}Serializer" Object.const_get "#{resource.class.name}Serializer"
@ -70,7 +74,11 @@ end
else else
def serializer_for(resource) def serializer_for(resource)
if resource.respond_to?(:to_ary) if resource.respond_to?(:to_ary)
ArraySerializer if Object.constants.include?(:ArraySerializer)
::ArraySerializer
else
ArraySerializer
end
else else
"#{resource.class.name}Serializer".safe_constantize "#{resource.class.name}Serializer".safe_constantize
end end

View File

@ -9,7 +9,7 @@ module ActiveModel
end end
def test_serializer_for_array_returns_appropriate_type def test_serializer_for_array_returns_appropriate_type
assert_kind_of ArraySerializer, @serializer assert_kind_of ActiveModel::ArraySerializer, @serializer
end end
def test_array_serializer_serializes_simple_objects def test_array_serializer_serializes_simple_objects
@ -18,6 +18,23 @@ module ActiveModel
end end
end end
class CustomArraySerializerSupport < Minitest::Test
def setup
Object.const_set(:ArraySerializer, Class.new{ def initialize(*); end })
array = [1, 2, 3]
@serializer = Serializer.serializer_for(array).new(array)
end
def teardown
Object.send(:remove_const, :ArraySerializer)
end
def test_serializer_for_array_returns_appropriate_type
assert_kind_of ::ArraySerializer, @serializer
end
end
class ModelSerializationTest < Minitest::Test class ModelSerializationTest < Minitest::Test
def test_array_serializer_serializes_models def test_array_serializer_serializes_models
array = [Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }), array = [Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }),