serega 0.51.1 → 0.52.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +49 -21
- data/VERSION +1 -1
- data/docs/README.md +42 -0
- data/docs/attributes.md +248 -0
- data/docs/batch-loading.md +207 -0
- data/docs/camel-case.md +86 -0
- data/docs/conditional-attributes.md +165 -0
- data/docs/configuration.md +47 -0
- data/docs/context.md +34 -0
- data/docs/errors.md +38 -0
- data/docs/formatters.md +262 -0
- data/docs/hash-records.md +93 -0
- data/docs/migrating-from-root-and-metadata.md +50 -0
- data/docs/preloads.md +125 -0
- data/docs/prepare-initial-objects.md +72 -0
- data/docs/presenter.md +87 -0
- data/docs/presets.md +174 -0
- data/docs/ractors.md +54 -0
- data/docs/relations.md +233 -0
- data/docs/responses-rails.md +287 -0
- data/docs/responses.md +293 -0
- data/docs/root-and-metadata.md +110 -0
- data/docs/selecting-fields.md +164 -0
- data/docs/serializing.md +113 -0
- data/docs/testing.md +230 -0
- data/lib/serega/attribute_normalizer.rb +26 -8
- data/lib/serega/attribute_normalizers/block.rb +3 -3
- data/lib/serega/config.rb +28 -13
- data/lib/serega/errors.rb +2 -2
- data/lib/serega/plan/cache.rb +13 -29
- data/lib/serega/plan/per_ractor_cache.rb +2 -2
- data/lib/serega/plan/point.rb +13 -2
- data/lib/serega/plan.rb +1 -1
- data/lib/serega/plugins/context_metadata/context_metadata.rb +5 -1
- data/lib/serega/plugins/metadata/metadata.rb +4 -0
- data/lib/serega/plugins/root/root.rb +14 -10
- data/lib/serega/plugins.rb +13 -0
- data/lib/serega/result_code/relation_point_code.rb +3 -2
- data/lib/serega/source_group.rb +1 -1
- data/lib/serega/validations/attribute/check_block.rb +4 -7
- data/lib/serega/validations/attribute/check_opt_hash_access.rb +2 -3
- data/lib/serega/validations/check_batch_loader_params.rb +2 -1
- data/lib/serega.rb +30 -26
- data/sig/serega.rbs +10 -8
- metadata +24 -1
data/docs/relations.md
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# Relations
|
|
2
|
+
|
|
3
|
+
A relation is an attribute serialized with another serializer: an attribute
|
|
4
|
+
with the `:serializer` option, or with a block that defines a
|
|
5
|
+
[nested serializer](#nested-serializers-defined-with-a-block).
|
|
6
|
+
|
|
7
|
+
```ruby
|
|
8
|
+
class PostSerializer < Serega
|
|
9
|
+
attribute :title
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
class UserSerializer < Serega
|
|
13
|
+
attribute :username
|
|
14
|
+
attribute :posts, serializer: PostSerializer, many: true
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
UserSerializer.to_h(user)
|
|
18
|
+
# => {username: "gru", posts: [{title: "Stealing the Moon"}]}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Table of Contents
|
|
22
|
+
|
|
23
|
+
<!-- toc -->
|
|
24
|
+
|
|
25
|
+
- [Relation options](#relation-options)
|
|
26
|
+
- [`:serializer`](#serializer)
|
|
27
|
+
- [`:many`](#many)
|
|
28
|
+
- [`:preset`](#preset)
|
|
29
|
+
- [`:only`, `:with`, `:except`](#only-with-except)
|
|
30
|
+
- [`:preload`](#preload)
|
|
31
|
+
- [Nested serializers defined with a block](#nested-serializers-defined-with-a-block)
|
|
32
|
+
- [Limiting nesting depth](#limiting-nesting-depth)
|
|
33
|
+
|
|
34
|
+
<!-- tocstop -->
|
|
35
|
+
|
|
36
|
+
## Relation options
|
|
37
|
+
|
|
38
|
+
### `:serializer`
|
|
39
|
+
|
|
40
|
+
Serializes the value with another serializer. Use a String or a Proc when
|
|
41
|
+
serializers refer to each other.
|
|
42
|
+
|
|
43
|
+
```ruby
|
|
44
|
+
attribute :posts, serializer: PostSerializer
|
|
45
|
+
attribute :posts, serializer: "PostSerializer"
|
|
46
|
+
attribute :posts, serializer: -> { PostSerializer }
|
|
47
|
+
# => {posts: [{title: "Stealing the Moon"}]}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### `:many`
|
|
51
|
+
|
|
52
|
+
Serega serializes a value as a list when it is an `Enumerable`, except `Hash`
|
|
53
|
+
and `Struct`. `many: true` marks a list explicitly and serializes `nil` as
|
|
54
|
+
`[]`.
|
|
55
|
+
|
|
56
|
+
```ruby
|
|
57
|
+
attribute :posts, serializer: PostSerializer, many: true
|
|
58
|
+
# => {posts: []} when user.posts is nil
|
|
59
|
+
# => {posts: [{title: "Stealing the Moon"}]} when user.posts is one post
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
A relation without `:many` follows `config.many` of its serializer, so a
|
|
63
|
+
serializer with `config.many = false` gets a list as one object, and a
|
|
64
|
+
serializer with `config.many = true` serializes `nil` as `[]`.
|
|
65
|
+
|
|
66
|
+
`config.require_many = true` requires `:many` on every relation, an
|
|
67
|
+
attribute with `:serializer` or a block. A relation without `:many` raises
|
|
68
|
+
`Serega::SeregaError`.
|
|
69
|
+
|
|
70
|
+
```ruby
|
|
71
|
+
class AppSerializer < Serega
|
|
72
|
+
config.require_many = true
|
|
73
|
+
config.base_serializer = self
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
class PostSerializer < AppSerializer
|
|
77
|
+
attribute :comments, serializer: CommentSerializer, many: true
|
|
78
|
+
attribute :author, many: false do
|
|
79
|
+
attribute :name
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### `:preset`
|
|
85
|
+
|
|
86
|
+
Serializes the fields of a preset of the relation serializer by default. The
|
|
87
|
+
options of the call merge with the preset. See [Preset on a relation](presets.md#preset-on-a-relation).
|
|
88
|
+
|
|
89
|
+
```ruby
|
|
90
|
+
attribute :posts, serializer: PostSerializer, many: true, preset: :summary
|
|
91
|
+
# => {posts: [{id: 1, title: "Stealing the Moon"}]}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### `:only`, `:with`, `:except`
|
|
95
|
+
|
|
96
|
+
Select the fields of the relation by default, like the same options of a
|
|
97
|
+
call. See [Field selection options of a relation](presets.md#field-selection-options-of-a-relation).
|
|
98
|
+
|
|
99
|
+
```ruby
|
|
100
|
+
attribute :posts, serializer: PostSerializer, many: true, only: [:id, :title]
|
|
101
|
+
# => {posts: [{id: 1, title: "Stealing the Moon"}]}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### `:preload`
|
|
105
|
+
|
|
106
|
+
Names the associations to preload for the value, so the value is read without
|
|
107
|
+
N+1 queries. See [Preloads](preloads.md).
|
|
108
|
+
|
|
109
|
+
```ruby
|
|
110
|
+
attribute :email, preload: :emails, value: proc { |user| user.emails.find(&:verified?) }
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Nested serializers defined with a block
|
|
114
|
+
|
|
115
|
+
A block defines an anonymous nested serializer for the attribute value. The
|
|
116
|
+
value is found as usual, by the attribute name or the `:method`, `:value`,
|
|
117
|
+
`:delegate` or `:batch` option.
|
|
118
|
+
|
|
119
|
+
```ruby
|
|
120
|
+
class UserSerializer < AppSerializer
|
|
121
|
+
attribute :first_name
|
|
122
|
+
|
|
123
|
+
# user.profile
|
|
124
|
+
attribute :profile do
|
|
125
|
+
attribute :city
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# The user itself, with only its counters
|
|
129
|
+
attribute :statistics, method: :itself do
|
|
130
|
+
attribute :likes_count
|
|
131
|
+
attribute :comments_count
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
UserSerializer.to_h(user)
|
|
136
|
+
# => {first_name: "Felonious", profile: {city: "Freedonia"}, statistics: {likes_count: 10, comments_count: 3}}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
The nested serializer is a subclass of a base serializer, set with
|
|
140
|
+
`config.base_serializer` or the `base_serializer:` attribute option. The
|
|
141
|
+
attribute option takes precedence. An attribute block raises
|
|
142
|
+
`Serega::SeregaError` when neither is set.
|
|
143
|
+
|
|
144
|
+
```ruby
|
|
145
|
+
attribute :statistics, method: :itself, base_serializer: StatisticsSerializer do
|
|
146
|
+
attribute :likes_count
|
|
147
|
+
end
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
The nested serializer inherits everything from its base serializer: plugins,
|
|
151
|
+
config, attributes, batch loaders and the preload handler. Anything else can be
|
|
152
|
+
declared inside the block:
|
|
153
|
+
|
|
154
|
+
```ruby
|
|
155
|
+
attribute :statistics, method: :itself do
|
|
156
|
+
batch :statistics, ->(users) { Statistics.for_users(users) } # => {user_id => statistics}
|
|
157
|
+
|
|
158
|
+
attribute :likes_count, batch: :statistics,
|
|
159
|
+
value: proc { |user, batches:| batches[:statistics][user.id].likes }
|
|
160
|
+
end
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Good to know:
|
|
164
|
+
|
|
165
|
+
- The nested serializer is created when the attribute is defined. Later
|
|
166
|
+
changes to the base serializer do not reach it.
|
|
167
|
+
- With a [presenter](presenter.md), `method: :itself` serializes the presenter.
|
|
168
|
+
`method: :__getobj__` serializes the original object.
|
|
169
|
+
- Errors name the nested serializer and the line where the attribute is
|
|
170
|
+
defined:
|
|
171
|
+
|
|
172
|
+
```text
|
|
173
|
+
(when serializing the 'likes_count' attribute in UserSerializer.<statistics>, app/serializers/user_serializer.rb:12)
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## Limiting nesting depth
|
|
177
|
+
|
|
178
|
+
`config.depth_limit` guards against expensive requests and cyclic relations.
|
|
179
|
+
The fields of the serializer itself are depth 1, so `1` allows no relations
|
|
180
|
+
and `2` allows one level of relations. The limit of the serializer that starts
|
|
181
|
+
the serialization applies to all nested serializers.
|
|
182
|
+
|
|
183
|
+
The limit counts only relations, the attributes with a `:serializer`. It does
|
|
184
|
+
not check attribute values: a Hash or an Array that a value returns is
|
|
185
|
+
serialized as it is, at any depth.
|
|
186
|
+
|
|
187
|
+
```ruby
|
|
188
|
+
class AppSerializer < Serega
|
|
189
|
+
config.depth_limit = 10
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
class UserSerializer < AppSerializer
|
|
193
|
+
config.depth_limit = 2
|
|
194
|
+
attribute :friends, serializer: -> { UserSerializer }, hide: true
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
UserSerializer.to_h(user, with: :friends) # depth 2
|
|
198
|
+
UserSerializer.to_h(user, with: {friends: :friends})
|
|
199
|
+
# => Serega::DepthLimitError: Depth limit was exceeded
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
`Serega::DepthLimitError#details` shows the path, and on the next line the
|
|
203
|
+
serializer whose limit applies:
|
|
204
|
+
|
|
205
|
+
```text
|
|
206
|
+
UserSerializer (depth limit: 2) -> friends -> friends
|
|
207
|
+
(hint: if the nesting is not a cycle, increase config.depth_limit of UserSerializer)
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
The message is `Depth limit was exceeded`, safe to show to API clients.
|
|
211
|
+
|
|
212
|
+
Without a limit, relations that nest in a cycle raise `Serega::DepthLimitError`
|
|
213
|
+
with the message `Relations nest in a cycle`. A cycle is a relation that
|
|
214
|
+
selects the same fields of a serializer that a level above it already selects,
|
|
215
|
+
for example `friends` shown by default in `UserSerializer`:
|
|
216
|
+
|
|
217
|
+
```ruby
|
|
218
|
+
class UserSerializer < Serega
|
|
219
|
+
attribute :friends, serializer: -> { UserSerializer }
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
UserSerializer.to_h(user)
|
|
223
|
+
# => Serega::DepthLimitError: Relations nest in a cycle
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
```text
|
|
227
|
+
UserSerializer -> friends
|
|
228
|
+
(hint: hide a relation of the cycle or set config.depth_limit)
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
The limit is checked when the serialization plan is built, before any
|
|
232
|
+
serialization. Call `UserSerializer.new(with: params[:with])` early to
|
|
233
|
+
validate a request before running other code.
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
# Responses in Rails
|
|
2
|
+
|
|
3
|
+
This guide adds Rails and ActiveRecord to
|
|
4
|
+
[Response Serializers](responses.md): it uses `Serializers::Base`,
|
|
5
|
+
`Serializers::Meta` and `Serializers::Response` from there. Like that guide,
|
|
6
|
+
it is an example: take the parts that fit your app.
|
|
7
|
+
|
|
8
|
+
## Table of Contents
|
|
9
|
+
|
|
10
|
+
<!-- toc -->
|
|
11
|
+
|
|
12
|
+
- [ActiveRecord](#activerecord)
|
|
13
|
+
- [Preloads instead of `includes`](#preloads-instead-of-includes)
|
|
14
|
+
- [Batch loading from a cache](#batch-loading-from-a-cache)
|
|
15
|
+
- [Paging with Kaminari](#paging-with-kaminari)
|
|
16
|
+
- [Controllers](#controllers)
|
|
17
|
+
- [A common context](#a-common-context)
|
|
18
|
+
- [Flash messages](#flash-messages)
|
|
19
|
+
- [Validation errors](#validation-errors)
|
|
20
|
+
|
|
21
|
+
<!-- tocstop -->
|
|
22
|
+
|
|
23
|
+
## ActiveRecord
|
|
24
|
+
|
|
25
|
+
### Preloads instead of `includes`
|
|
26
|
+
|
|
27
|
+
`plugin :activerecord_preloads` with `config.auto_preload = true` preloads the
|
|
28
|
+
relations of the serialized fields, so the query needs no `includes` or
|
|
29
|
+
`preload`: the serializer knows which relations the client requested.
|
|
30
|
+
|
|
31
|
+
```ruby
|
|
32
|
+
module Serializers
|
|
33
|
+
class Base < Serega
|
|
34
|
+
plugin :activerecord_preloads
|
|
35
|
+
config.auto_preload = true
|
|
36
|
+
config.hide_by_default = :auto
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
class Post < Base
|
|
40
|
+
attribute :id
|
|
41
|
+
attribute :title
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
class User < Base
|
|
45
|
+
attribute :id
|
|
46
|
+
attribute :name
|
|
47
|
+
attribute :posts, serializer: Post, many: true # preloads :posts
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
users = User.order(:id).limit(20)
|
|
52
|
+
USERS_SERIALIZER.to_json(users)
|
|
53
|
+
# SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 20
|
|
54
|
+
# => {"data":[{"id":1,"name":"Felonious Gru"}],"meta":{"version":"1"}}
|
|
55
|
+
|
|
56
|
+
USERS_SERIALIZER.to_json(users, with: "data(posts)") # users are loaded already
|
|
57
|
+
# SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, ...)
|
|
58
|
+
# => {"data":[{"id":1,"name":"Felonious Gru","posts":[{"id":1,"title":"Freedonia"}]}],"meta":{"version":"1"}}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`posts` has a preload, so `hide_by_default = :auto` hides it until a client
|
|
62
|
+
requests it. With `includes(:posts)` in the query, the first call loads the
|
|
63
|
+
posts it doesn't serialize. See [Preloads](preloads.md).
|
|
64
|
+
|
|
65
|
+
### Batch loading from a cache
|
|
66
|
+
|
|
67
|
+
A value that is not a relation, for example a value in a cache, loads with a
|
|
68
|
+
[batch loader](batch-loading.md): one cache read for all users, not one per
|
|
69
|
+
user.
|
|
70
|
+
|
|
71
|
+
```ruby
|
|
72
|
+
module Serializers
|
|
73
|
+
class User < Base
|
|
74
|
+
# One read_multi for all users; returns {user_id => value}
|
|
75
|
+
batch :last_seen_at, lambda { |users|
|
|
76
|
+
keys = users.to_h { |user| ["users/#{user.id}/last_seen_at", user.id] }
|
|
77
|
+
Rails.cache.read_multi(*keys.keys).transform_keys(keys)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
attribute :id
|
|
81
|
+
attribute :name
|
|
82
|
+
attribute :last_seen_at, batch: true
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`last_seen_at` has a batch loader, so it is hidden too:
|
|
88
|
+
`with: "data(last_seen_at)"` requests it, and only then the cache is read.
|
|
89
|
+
`Rails.cache` stands for any ActiveSupport cache store; other caches need a
|
|
90
|
+
multi-get, such as Redis `MGET`.
|
|
91
|
+
|
|
92
|
+
### Paging with Kaminari
|
|
93
|
+
|
|
94
|
+
`Paging` serializes the Kaminari methods of a scope. `Meta` adds it only for
|
|
95
|
+
a scope paged with Kaminari: `.page` on a relation or
|
|
96
|
+
`Kaminari.paginate_array`. A record, an Array or a scope without `.page` skip
|
|
97
|
+
it, see [Conditional Attributes](conditional-attributes.md).
|
|
98
|
+
|
|
99
|
+
```ruby
|
|
100
|
+
module Serializers
|
|
101
|
+
class Paging < Base
|
|
102
|
+
attribute :page, method: :current_page
|
|
103
|
+
attribute :per_page, method: :limit_value
|
|
104
|
+
attribute :total_count
|
|
105
|
+
attribute :total_pages
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
class Meta < Base
|
|
109
|
+
attribute :version, const: "1"
|
|
110
|
+
attribute :request_id, value: proc { |_object, ctx| ctx[:request_id] }, unless_value: :nil?
|
|
111
|
+
|
|
112
|
+
attribute :paging, serializer: Paging, method: :itself, many: false, # the scope as one object
|
|
113
|
+
if: proc { |object| object.is_a?(Kaminari::PageScopeMethods) } # only Kaminari scopes
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
users = User.order(:id).page(1).per(20)
|
|
118
|
+
USERS_SERIALIZER.to_json(users, only: "meta")
|
|
119
|
+
# => {"meta":{"version":"1","paging":{"page":1,"per_page":20,"total_count":1,"total_pages":1}}}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Without `many: false` on `paging`, Serega calls the methods of `Paging` on
|
|
123
|
+
each user and raises
|
|
124
|
+
`NoMethodError: undefined method 'current_page' for an instance of User`.
|
|
125
|
+
See [Why `many: false`](responses.md#why-many-false).
|
|
126
|
+
|
|
127
|
+
## Controllers
|
|
128
|
+
|
|
129
|
+
In this example, controllers keep the response serializers in constants and
|
|
130
|
+
render JSON with `json`, an `ApplicationController` method that adds the
|
|
131
|
+
[common context](#a-common-context):
|
|
132
|
+
|
|
133
|
+
```ruby
|
|
134
|
+
class UsersController < ApplicationController
|
|
135
|
+
USER_SERIALIZER = Serializers::Response.one(Serializers::User)
|
|
136
|
+
USERS_SERIALIZER = Serializers::Response.list(Serializers::User)
|
|
137
|
+
|
|
138
|
+
def index
|
|
139
|
+
users = User.order(:id).page(params[:page]).per(20)
|
|
140
|
+
render json: json(USERS_SERIALIZER, users)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def show
|
|
144
|
+
user = User.find(params[:id])
|
|
145
|
+
render json: json(USER_SERIALIZER, user)
|
|
146
|
+
end
|
|
147
|
+
end
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## A common context
|
|
151
|
+
|
|
152
|
+
Most responses need the same [context](context.md): the current user, the
|
|
153
|
+
request id. This example builds it in one method of `ApplicationController`,
|
|
154
|
+
as a serializer has no access to the request. `json` serializes with it, and
|
|
155
|
+
with the fields the request [selects](responses.md#selecting-fields) in its `only`,
|
|
156
|
+
`with`, `except` and `preset` parameters:
|
|
157
|
+
|
|
158
|
+
```ruby
|
|
159
|
+
class ApplicationController < ActionController::API
|
|
160
|
+
rescue_from Serega::AttributeNotExist, Serega::PresetNotExist do |error|
|
|
161
|
+
render json: {errors: [{source: "fields", title: error.message}]}, status: :bad_request
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
private
|
|
165
|
+
|
|
166
|
+
# The context of every response
|
|
167
|
+
def serialization_context
|
|
168
|
+
{
|
|
169
|
+
request_id: request.request_id,
|
|
170
|
+
current_user: proc { current_user } # found only when a serialized field reads it
|
|
171
|
+
}
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# JSON of the serializer with the fields of the request and the common
|
|
175
|
+
# context; `context:` adds to it
|
|
176
|
+
def json(serializer, object, context: {})
|
|
177
|
+
serializer.to_json(
|
|
178
|
+
object,
|
|
179
|
+
only: params[:only],
|
|
180
|
+
with: params[:with],
|
|
181
|
+
except: params[:except],
|
|
182
|
+
preset: params[:preset],
|
|
183
|
+
context: serialization_context.merge(context)
|
|
184
|
+
)
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`current_user: current_user` works too, but it finds the user for every
|
|
190
|
+
response. With a proc, a response finds the user only when a requested field
|
|
191
|
+
reads it, so a public response with no user-specific fields skips the lookup:
|
|
192
|
+
|
|
193
|
+
```ruby
|
|
194
|
+
module Serializers
|
|
195
|
+
class User < Base
|
|
196
|
+
attribute :id
|
|
197
|
+
attribute :name
|
|
198
|
+
attribute :editable, hide: true, value: proc { |user, ctx| user == ctx[:current_user].call }
|
|
199
|
+
end
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
```text
|
|
205
|
+
GET /users
|
|
206
|
+
{"data":[{"id":1,"name":"Felonious Gru"},{"id":2,"name":"Lucy"}],"meta":{"version":"1","request_id":"f3a9"}}
|
|
207
|
+
The proc is not called, so the user is not found.
|
|
208
|
+
|
|
209
|
+
GET /users?with=data(editable)
|
|
210
|
+
{"data":[{"id":1,"name":"Felonious Gru","editable":true},{"id":2,"name":"Lucy","editable":false}],
|
|
211
|
+
"meta":{"version":"1","request_id":"f3a9"}}
|
|
212
|
+
|
|
213
|
+
GET /users?only=data(nickname)
|
|
214
|
+
400 {"errors":[{"source":"fields","title":"Not existing attributes: data(nickname)"}]}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
A `:value` proc runs once per object, so the proc runs once per user. Rails
|
|
218
|
+
apps usually memoize `current_user`, which keeps the lookup to one query; a
|
|
219
|
+
[batch loader](batch-loading.md#values-for-the-current-user) calls the proc
|
|
220
|
+
once per serialization. Where there is no request, as in a mailer, pass
|
|
221
|
+
`current_user: proc {}`, and the same serializers work.
|
|
222
|
+
|
|
223
|
+
## Flash messages
|
|
224
|
+
|
|
225
|
+
`notice` and `alert`, the names of Rails flash messages, can go to `meta` the
|
|
226
|
+
same way as `request_id`: pass them in the context, and add them to `Meta`.
|
|
227
|
+
|
|
228
|
+
```ruby
|
|
229
|
+
attribute :notice, value: proc { |_object, ctx| ctx[:notice] }, unless_value: :nil?
|
|
230
|
+
attribute :alert, value: proc { |_object, ctx| ctx[:alert] }, unless_value: :nil?
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
API-only apps have no flash, so the controller adds the messages itself:
|
|
234
|
+
`json(USERS_SERIALIZER, users, context: {notice: "Users imported"})`. Other
|
|
235
|
+
apps add them to `serialization_context`:
|
|
236
|
+
`notice: flash[:notice], alert: flash[:alert]`.
|
|
237
|
+
|
|
238
|
+
## Validation errors
|
|
239
|
+
|
|
240
|
+
This example renders validation errors as `{errors: [...]}`; give them the
|
|
241
|
+
shape your API uses. `ActiveModel::Errors#objects` returns
|
|
242
|
+
`ActiveModel::Error` objects, so a serializer reads them like any records.
|
|
243
|
+
Error serializers inherit `Serega` directly: they need none of the config and
|
|
244
|
+
plugins of `Base`.
|
|
245
|
+
|
|
246
|
+
```ruby
|
|
247
|
+
module Serializers
|
|
248
|
+
class Error < Serega
|
|
249
|
+
attribute :source, method: :attribute
|
|
250
|
+
attribute :title, method: :message
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
# The errors of one record as one response
|
|
254
|
+
class Errors < Serega
|
|
255
|
+
config.many = false # one {errors:}, not one response per error
|
|
256
|
+
attribute :errors, serializer: Error, method: :objects, many: true # ActiveModel::Error objects
|
|
257
|
+
end
|
|
258
|
+
end
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
`create!` and `update!` raise `ActiveRecord::RecordInvalid` for an invalid
|
|
262
|
+
record. Here actions don't check for errors, and one handler in
|
|
263
|
+
`ApplicationController` renders the errors of every action:
|
|
264
|
+
|
|
265
|
+
```ruby
|
|
266
|
+
class ApplicationController < ActionController::API
|
|
267
|
+
rescue_from ActiveRecord::RecordInvalid do |error|
|
|
268
|
+
errors = error.record.errors
|
|
269
|
+
render json: Serializers::Errors.to_json(errors), status: :unprocessable_entity
|
|
270
|
+
end
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
class UsersController < ApplicationController
|
|
274
|
+
def create
|
|
275
|
+
user = User.create!(user_params) # raises ActiveRecord::RecordInvalid for an invalid user
|
|
276
|
+
render json: json(USER_SERIALIZER, user), status: :created
|
|
277
|
+
end
|
|
278
|
+
end
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
```text
|
|
282
|
+
POST /users {"user":{"name":""}}
|
|
283
|
+
422 {"errors":[{"source":"name","title":"can't be blank"}]}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
A serializer named `Serializers::User` lives in a file that your autoloader
|
|
287
|
+
maps to that name, for example `app/serializers/serializers/user.rb`.
|