Skip to content

Commit 46ae776

Browse files
committed
Merge pull request #897 from imanel/patch-1
Allow to define custom serializer for given class
2 parents ece43f3 + c91b649 commit 46ae776

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

lib/active_model/serializer.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,9 @@ def self.urls(*attrs)
115115
end
116116

117117
def self.serializer_for(resource, options = {})
118-
if resource.respond_to?(:to_ary)
118+
if resource.respond_to?(:serializer_class)
119+
resource.serializer_class
120+
elsif resource.respond_to?(:to_ary)
119121
config.array_serializer
120122
else
121123
options

test/serializers/serializer_for_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,14 @@ def test_overwritten_serializer_for_array
2929
class SerializerTest < Minitest::Test
3030
class MyProfile < Profile
3131
end
32+
class CustomProfile
33+
def serializer_class; ProfileSerializer; end
34+
end
3235

3336
def setup
3437
@profile = Profile.new
3538
@my_profile = MyProfile.new
39+
@custom_profile = CustomProfile.new
3640
@model = ::Model.new
3741
end
3842

@@ -50,6 +54,11 @@ def test_serializer_inherited_serializer
5054
serializer = ActiveModel::Serializer.serializer_for(@my_profile)
5155
assert_equal ProfileSerializer, serializer
5256
end
57+
58+
def test_serializer_custom_serializer
59+
serializer = ActiveModel::Serializer.serializer_for(@custom_profile)
60+
assert_equal ProfileSerializer, serializer
61+
end
5362
end
5463
end
5564
end

0 commit comments

Comments
 (0)