Skip to content

Commit d67f7da

Browse files
bdmacbf4
authored andcommitted
Preserve the serializer type when fragment caching
We were not previously cloning the type setting into the dynamically generated cached/non-cached serializers for a given fragment-cached serializer. This led to the type generated for JsonApi having the wrong value when fragment caching is enabled by adding either :except or :only options to cache. This pulls the type setting from the fragment-cached serializer forward onto the dynamic caching classes so it is preserved in the output.
1 parent 8981683 commit d67f7da

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

lib/active_model/serializer/adapter/fragment_cache.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ def fragment_serializer(name, klass)
9494

9595
cached.constantize.cache(klass._cache_options)
9696

97+
# Preserve the type setting in the cached/non-cached serializer classes
98+
cached.constantize.type(klass._type)
99+
non_cached.constantize.type(klass._type)
100+
97101
cached.constantize.fragmented(serializer)
98102
non_cached.constantize.fragmented(serializer)
99103

test/adapter/fragment_cache_test.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,14 @@ module ActiveModel
33
class Serializer
44
module Adapter
55
class FragmentCacheTest < ActiveSupport::TestCase
6+
TypedRoleSerializer = Class.new(ActiveModel::Serializer) do
7+
type 'my-roles'
8+
cache only: [:name], skip_digest: true
9+
attributes :id, :name, :description
10+
11+
belongs_to :author
12+
end
13+
614
def setup
715
super
816
@spam = Spam::UnrelatedLink.new(id: 'spam-id-1')
@@ -31,8 +39,12 @@ def test_fragment_fetch_with_namespaced_object
3139
}
3240
assert_equal(@spam_hash.fetch, expected_result)
3341
end
42+
43+
def test_fragment_fetch_with_type_override
44+
serialization = serializable(Role.new(name: 'Another Author'), serializer: TypedRoleSerializer, adapter: :json_api).serializable_hash
45+
assert_equal(TypedRoleSerializer._type, serialization.fetch(:data).fetch(:type))
46+
end
3447
end
3548
end
3649
end
3750
end
38-

0 commit comments

Comments
 (0)