@@ -13,7 +13,7 @@ class BlogSerializer < ActiveModel::Serializer
13
13
Rails . configuration . serializers << BlogSerializer
14
14
15
15
class CommentSerializer < ActiveModel ::Serializer
16
- attributes :id , :body
16
+ attributes :id , :body , :updated_at
17
17
18
18
belongs_to :post
19
19
belongs_to :author
@@ -43,7 +43,7 @@ def blog
43
43
Rails . configuration . serializers << PostSerializer
44
44
45
45
class CachingAuthorSerializer < AuthorSerializer
46
- cache key : 'writer' , only : [ :first_name , :last_name ] , skip_digest : true
46
+ cache key : 'writer' , skip_digest : true
47
47
end
48
48
Rails . configuration . serializers << CachingAuthorSerializer
49
49
@@ -58,9 +58,9 @@ class CachingPostSerializer < ActiveModel::Serializer
58
58
59
59
attributes :id , :title , :body
60
60
61
- has_many :comments , serializer : CommentSerializer
62
61
belongs_to :blog , serializer : BlogSerializer
63
- belongs_to :author , serializer : AuthorSerializer
62
+ belongs_to :author , serializer : CachingAuthorSerializer
63
+ has_many :comments , serializer : CachingCommentSerializer
64
64
65
65
link ( :post_authors ) { 'https://example.com/post_authors' }
66
66
@@ -77,6 +77,41 @@ def blog
77
77
end
78
78
Rails . configuration . serializers << CachingPostSerializer
79
79
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
+
80
115
if ENV [ 'ENABLE_ACTIVE_RECORD' ] == 'true'
81
116
require 'active_record'
82
117
@@ -167,7 +202,7 @@ def read_attribute_for_serialization(key)
167
202
end
168
203
169
204
class Comment < BenchmarkModel
170
- attr_accessor :id , :body
205
+ attr_accessor :id , :body , :updated_at
171
206
end
172
207
173
208
class Author < BenchmarkModel
0 commit comments