Skip to content

Allow to define custom serializer for given class #813

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ def format_keys(format)
attr_reader :key_format

def serializer_for(resource, options = {})
if resource.respond_to?(:to_ary)
if resource.respond_to?(:serializer_class)
resource.serializer_class
elsif resource.respond_to?(:to_ary)
if Object.constants.include?(:ArraySerializer)
::ArraySerializer
else
Expand Down
17 changes: 17 additions & 0 deletions test/unit/active_model/array_serializer/serialization_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,23 @@ def test_serializer_for_array_returns_appropriate_type
end
end

class CustomSerializerClassTest < Minitest::Test
def setup
Object.const_set(:CustomSerializer, Class.new)
end

def teardown
Object.send(:remove_const, :CustomSerializer)
end

def test_serializer_for_array_returns_appropriate_type
object = {}
def object.serializer_class; CustomSerializer; end

assert_equal CustomSerializer, Serializer.serializer_for(object)
end
end

class ModelSerializationTest < Minitest::Test
def test_array_serializer_serializes_models
array = [Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }),
Expand Down