Skip to content

Commit

Permalink
Allow to define custom serializer for given class by defining #serial…
Browse files Browse the repository at this point in the history
…izer_class method in serialized object's class. Resolves rails-api#515.
  • Loading branch information
imanel committed May 3, 2015
1 parent 6a06b90 commit c91b649
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ def self.urls(*attrs)
end

def self.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)
config.array_serializer
else
options
Expand Down
9 changes: 9 additions & 0 deletions test/serializers/serializer_for_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,14 @@ def test_overwritten_serializer_for_array
class SerializerTest < Minitest::Test
class MyProfile < Profile
end
class CustomProfile
def serializer_class; ProfileSerializer; end
end

def setup
@profile = Profile.new
@my_profile = MyProfile.new
@custom_profile = CustomProfile.new
@model = ::Model.new
end

Expand All @@ -50,6 +54,11 @@ def test_serializer_inherited_serializer
serializer = ActiveModel::Serializer.serializer_for(@my_profile)
assert_equal ProfileSerializer, serializer
end

def test_serializer_custom_serializer
serializer = ActiveModel::Serializer.serializer_for(@custom_profile)
assert_equal ProfileSerializer, serializer
end
end
end
end
Expand Down

0 comments on commit c91b649

Please sign in to comment.