Merge pull request #594 from bolshakov/feature/custom_array_serializer

Support custom array serializer
This commit is contained in:
Steve Klabnik 2014-08-22 15:28:26 -04:00
commit 74625f778b
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)
array = [1, 2, 3]
@serializer_class = Serializer.serializer_for(array)
end
def teardown
Object.send(:remove_const, :ArraySerializer)
end
def test_serializer_for_array_returns_appropriate_type
assert_equal ::ArraySerializer, @serializer_class
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' }),