mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
Allow to define custom serializer for given class by defining #serializer_class method in serialized object's class. Resolves #515.
This commit is contained in:
parent
6a06b90743
commit
c91b649504
@ -115,7 +115,9 @@ module ActiveModel
|
|||||||
end
|
end
|
||||||
|
|
||||||
def self.serializer_for(resource, options = {})
|
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
|
config.array_serializer
|
||||||
else
|
else
|
||||||
options
|
options
|
||||||
|
|||||||
@ -29,10 +29,14 @@ module ActiveModel
|
|||||||
class SerializerTest < Minitest::Test
|
class SerializerTest < Minitest::Test
|
||||||
class MyProfile < Profile
|
class MyProfile < Profile
|
||||||
end
|
end
|
||||||
|
class CustomProfile
|
||||||
|
def serializer_class; ProfileSerializer; end
|
||||||
|
end
|
||||||
|
|
||||||
def setup
|
def setup
|
||||||
@profile = Profile.new
|
@profile = Profile.new
|
||||||
@my_profile = MyProfile.new
|
@my_profile = MyProfile.new
|
||||||
|
@custom_profile = CustomProfile.new
|
||||||
@model = ::Model.new
|
@model = ::Model.new
|
||||||
end
|
end
|
||||||
|
|
||||||
@ -50,6 +54,11 @@ module ActiveModel
|
|||||||
serializer = ActiveModel::Serializer.serializer_for(@my_profile)
|
serializer = ActiveModel::Serializer.serializer_for(@my_profile)
|
||||||
assert_equal ProfileSerializer, serializer
|
assert_equal ProfileSerializer, serializer
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_serializer_custom_serializer
|
||||||
|
serializer = ActiveModel::Serializer.serializer_for(@custom_profile)
|
||||||
|
assert_equal ProfileSerializer, serializer
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user