@@ -13,7 +13,7 @@ class BlogSerializer < ActiveModel::Serializer
1313Rails . configuration . serializers << BlogSerializer
1414
1515class CommentSerializer < ActiveModel ::Serializer
16- attributes :id , :body
16+ attributes :id , :body , :updated_at
1717
1818 belongs_to :post
1919 belongs_to :author
@@ -43,7 +43,7 @@ def blog
4343Rails . configuration . serializers << PostSerializer
4444
4545class CachingAuthorSerializer < AuthorSerializer
46- cache key : 'writer' , only : [ :first_name , :last_name ] , skip_digest : true
46+ cache key : 'writer' , skip_digest : true
4747end
4848Rails . configuration . serializers << CachingAuthorSerializer
4949
@@ -58,9 +58,9 @@ class CachingPostSerializer < ActiveModel::Serializer
5858
5959 attributes :id , :title , :body
6060
61- has_many :comments , serializer : CommentSerializer
6261 belongs_to :blog , serializer : BlogSerializer
63- belongs_to :author , serializer : AuthorSerializer
62+ belongs_to :author , serializer : CachingAuthorSerializer
63+ has_many :comments , serializer : CachingCommentSerializer
6464
6565 link ( :post_authors ) { 'https://example.com/post_authors' }
6666
@@ -77,6 +77,41 @@ def blog
7777end
7878Rails . configuration . serializers << CachingPostSerializer
7979
80+ class FragmentCachingAuthorSerializer < AuthorSerializer
81+ cache key : 'writer' , only : [ :first_name , :last_name ] , skip_digest : true
82+ end
83+ Rails . configuration . serializers << FragmentCachingAuthorSerializer
84+
85+ class FragmentCachingCommentSerializer < CommentSerializer
86+ cache expires_in : 1 . day , except : [ :updated_at ] , skip_digest : true
87+ end
88+ Rails . configuration . serializers << CachingCommentSerializer
89+
90+ # see https://github.com/rails-api/active_model_serializers/pull/1690/commits/68715b8f99bc29677e8a47bb3f305f23c077024b#r60344532
91+ class FragmentCachingPostSerializer < ActiveModel ::Serializer
92+ cache key : 'post' , expires_in : 0.1 , skip_digest : true
93+
94+ attributes :id , :title , :body
95+
96+ belongs_to :blog , serializer : BlogSerializer
97+ belongs_to :author , serializer : FragmentCachingAuthorSerializer
98+ has_many :comments , serializer : FragmentCachingCommentSerializer
99+
100+ link ( :post_authors ) { 'https://example.com/post_authors' }
101+
102+ meta do
103+ {
104+ rating : 5 ,
105+ favorite_count : 10
106+ }
107+ end
108+
109+ def blog
110+ Blog . new ( id : 999 , name : 'Custom blog' )
111+ end
112+ end
113+ Rails . configuration . serializers << FragmentCachingPostSerializer
114+
80115if ENV [ 'ENABLE_ACTIVE_RECORD' ] == 'true'
81116 require 'active_record'
82117
@@ -167,7 +202,7 @@ def read_attribute_for_serialization(key)
167202 end
168203
169204 class Comment < BenchmarkModel
170- attr_accessor :id , :body
205+ attr_accessor :id , :body , :updated_at
171206 end
172207
173208 class Author < BenchmarkModel
0 commit comments