serega 0.52.0 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0e0bf08e498468db05502a670ba2d980e8c1294b909e63c2a5e7b647b543fb83
4
- data.tar.gz: 15fe428ba2c61ee524d701210048c9d26af1078ec5bbc476beb8f7b320d27d67
3
+ metadata.gz: b19802c6b8dd4a72ac21db0b8e461b7b86d1435ef79defd50d1a9db68218c343
4
+ data.tar.gz: 78a3195fe0276c4735caf46f5394c4b22a760e55cfbd931cc51fb4dd1aa8bf39
5
5
  SHA512:
6
- metadata.gz: 5d6ddc6a0b696369c0210bd324105fb02f6e9713c9e4d31c188492174371f35aaa9a62d06a2384d75cdafa4cbdbea8faa40dc9db58bccaafc363d9b6d8853351
7
- data.tar.gz: dbac978f6f5a302cdf764436e2faa5b9ce88fd55282c910b881f9a030031e1bae4a21b9fd3075821d7753b57b849138facf3351a0aa1c48bc78154b2a0f3621a
6
+ metadata.gz: 47611800440f9df6dfad0c891463190d85ddc87445ac10cfef3256f80db7d9b31c69e3bf3ecd130f9b3bf50be23b69587c7dd9ab3f42323e12fef6b45b855859
7
+ data.tar.gz: f01dc72ec6f16ca98ffb7b57a76803d5765975d603fcde7ad17313539d07711566e1c863220cafd334fc8ed3b47be5f7a6b48f7dc1430cd37eb3ff606346cb41
data/README.md CHANGED
@@ -192,6 +192,7 @@ Ractor.new(user) { |user| UserSerializer.to_h(user) }.value
192
192
  - [Prepare initial objects](docs/prepare-initial-objects.md) — serialize records by ids
193
193
  - [Configuration](docs/configuration.md) — all config options
194
194
  - [Response serializers](docs/responses.md) — wrap results in `{data: ..., meta: ...}`
195
+ - [Responses in Rails](docs/responses-rails.md) — controllers, ActiveRecord preloads, paging, errors
195
196
 
196
197
  ## Benchmarks
197
198
 
data/VERSION CHANGED
@@ -1 +1 @@
1
- 0.52.0
1
+ 0.52.1
data/docs/README.md CHANGED
@@ -9,6 +9,7 @@ see the [Cheatsheet](https://github.com/andreyruby/serega/blob/master/CHEATSHEET
9
9
  - [Relations](relations.md) — nested serializers, `:many`, depth limit
10
10
  - [Serializing](serializing.md) — `to_h`, `to_struct`, `to_data`
11
11
  - [Response Serializers](responses.md) — wrap results in `{data: ..., meta: ...}`
12
+ - [Responses in Rails](responses-rails.md) — controllers, ActiveRecord preloads, paging, errors
12
13
  with a serializer
13
14
  - [Root Key and Metadata](root-and-metadata.md) — deprecated plugins, see
14
15
  Response Serializers
data/docs/formatters.md CHANGED
@@ -23,11 +23,16 @@ Child serializers get the formatters of their parents. Define a formatter
23
23
  before the attributes that use it: `format: :money` with no `:money`
24
24
  formatter defined yet raises `Serega::SeregaError`.
25
25
 
26
+ A formatter also receives `nil`: `[:iso8601, 3]` on a missing time raises
27
+ `NoMethodError`. Add `allow_nil: true` to a formatter of a value that can be
28
+ `nil`, see [Formatting `nil` values](#formatting-nil-values).
29
+
26
30
  ## Table of Contents
27
31
 
28
32
  <!-- toc -->
29
33
 
30
34
  - [Formatter kinds](#formatter-kinds)
35
+ - [Formatting `nil` values](#formatting-nil-values)
31
36
  - [Formatters without a name](#formatters-without-a-name)
32
37
  - [Common formatters](#common-formatters)
33
38
  - [Times for JavaScript clients (`:iso8601`)](#times-for-javascript-clients-iso8601)
@@ -39,7 +44,6 @@ formatter defined yet raises `Serega::SeregaError`.
39
44
  - [API type names (`:type`)](#api-type-names-type)
40
45
  - [Money (`:money`)](#money-money)
41
46
  - [Decimals in JSON](#decimals-in-json)
42
- - [Formatting `nil` values](#formatting-nil-values)
43
47
 
44
48
  <!-- tocstop -->
45
49
 
@@ -76,6 +80,30 @@ of the value works, from Ruby, ActiveSupport or your own classes.
76
80
  A method formatter is called directly in the generated serialization code,
77
81
  which makes it the fastest kind.
78
82
 
83
+ ## Formatting `nil` values
84
+
85
+ A formatter formats `nil` too: a callable receives `nil`, and a method is
86
+ called on `nil`. With `allow_nil: true` a `nil` value stays `nil`.
87
+
88
+ ```ruby
89
+ formatter :iso8601, [:iso8601, 3], allow_nil: true
90
+ attribute :rating, format: {use: [:round, 1], allow_nil: true}
91
+ ```
92
+
93
+ A [`:default`](attributes.md#default) value is formatted too.
94
+
95
+ `:if_value` and `:unless_value` check the formatted value. Without
96
+ `allow_nil: true`, a formatter that turns `nil` into `0.0` keeps the
97
+ attribute that `unless_value: :nil?` should skip:
98
+
99
+ ```ruby
100
+ attribute :rating, format: ->(rating) { rating.to_f.round(1) }, unless_value: :nil?
101
+ # => {rating: 0.0} for a nil rating
102
+
103
+ attribute :rating, format: {use: ->(rating) { rating.to_f.round(1) }, allow_nil: true}, unless_value: :nil?
104
+ # => {} for a nil rating
105
+ ```
106
+
79
107
  ## Formatters without a name
80
108
 
81
109
  `:format` also accepts a formatter directly. A Symbol is always a formatter
@@ -87,6 +115,8 @@ attribute :email, format: ->(email) { email.downcase }
87
115
  attribute :nickname, format: {use: :upcase, allow_nil: true}
88
116
  ```
89
117
 
118
+ `allow_nil:` needs the Hash form, with the formatter under `:use`.
119
+
90
120
  ## Common formatters
91
121
 
92
122
  Examples of formatters that many APIs use. Copy the ones you need, for
@@ -203,6 +233,19 @@ Serega returns a `BigDecimal` as is, and `to_json` writes it with
203
233
  scientific notation: `"0.51501364e2"`. With ActiveSupport, as in Rails, it
204
234
  writes `"51.501364"`. A formatter gives the same output in both cases.
205
235
 
236
+ ```ruby
237
+ class PlaceSerializer < Serega
238
+ attribute :latitude
239
+ attribute :longitude
240
+ end
241
+
242
+ PlaceSerializer.to_json(place)
243
+ # => "{\"latitude\":\"0.51501364e2\",\"longitude\":\"-0.14189e0\"}" without ActiveSupport
244
+ # => "{\"latitude\":\"51.501364\",\"longitude\":\"-0.14189\"}" with ActiveSupport
245
+ ```
246
+
247
+ With a formatter, the decimals are JSON numbers:
248
+
206
249
  ```ruby
207
250
  class PlaceSerializer < Serega
208
251
  # JSON numbers: value.to_f
@@ -217,15 +260,3 @@ PlaceSerializer.to_json(place)
217
260
  A Float keeps about 17 significant digits, thus `to_f` rounds longer decimals:
218
261
  `BigDecimal("12345678901234567.89").to_f` is `1.2345678901234568e+16`. For a
219
262
  String with every digit, use `format: [:to_s, "F"]`.
220
-
221
- ## Formatting `nil` values
222
-
223
- A formatter formats `nil` too: a callable receives `nil`, and a method is
224
- called on `nil`. With `allow_nil: true` a `nil` value stays `nil`.
225
-
226
- ```ruby
227
- formatter :iso8601, [:iso8601, 3], allow_nil: true
228
- attribute :rating, format: {use: [:round, 1], allow_nil: true}
229
- ```
230
-
231
- A [`:default`](attributes.md#default) value is formatted too.
@@ -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`.
data/docs/responses.md CHANGED
@@ -3,7 +3,8 @@
3
3
  In this guide, a response serializer wraps the records of an API response
4
4
  with `data` and adds `meta`, such as paging. It is a plain serializer with a
5
5
  `data` and a `meta` attribute, so it uses the attribute options you already
6
- know, and clients select its fields from the root.
6
+ know, and clients select its fields from the root, for example
7
+ `?only=data(id,name)` (see [Selecting fields](#selecting-fields)).
7
8
 
8
9
  ```json
9
10
  {
@@ -15,9 +16,10 @@ know, and clients select its fields from the root.
15
16
  This guide is an example: one of many ways to structure API responses. Take
16
17
  the parts that fit your API and change the rest.
17
18
 
18
- The steps work in any Ruby app. The sections after them add what depends on
19
- the records and the framework: ActiveRecord preloads and paging, batch loading
20
- for other records, and a Rails controller.
19
+ The examples work in any Ruby app with any records: plain objects, Hashes,
20
+ or records from an HTTP API. [Responses in Rails](responses-rails.md) adds
21
+ ActiveRecord preloads instead of `includes`, Kaminari paging, controllers and
22
+ validation errors.
21
23
 
22
24
  Response serializers replace the [root and metadata plugins](root-and-metadata.md),
23
25
  see [Migrating from the Root and Metadata Plugins](migrating-from-root-and-metadata.md).
@@ -31,16 +33,8 @@ see [Migrating from the Root and Metadata Plugins](migrating-from-root-and-metad
31
33
  - [2. Describe `meta`](#2-describe-meta)
32
34
  - [3. Add a common response shape](#3-add-a-common-response-shape)
33
35
  - [4. Serialize responses](#4-serialize-responses)
34
- - [ActiveRecord](#activerecord)
35
- - [Preloads instead of `includes`](#preloads-instead-of-includes)
36
- - [Batch loading from a cache](#batch-loading-from-a-cache)
37
- - [Paging with Kaminari](#paging-with-kaminari)
38
- - [Without ActiveRecord](#without-activerecord)
39
- - [Rails](#rails)
40
- - [Controllers](#controllers)
41
- - [A common context](#a-common-context)
42
- - [Flash messages](#flash-messages)
43
- - [Validation errors](#validation-errors)
36
+ - [Loading values in batches](#loading-values-in-batches)
37
+ - [Paging](#paging)
44
38
  - [Fields serialized by default](#fields-serialized-by-default)
45
39
  - [Another mode for some serializers](#another-mode-for-some-serializers)
46
40
  - [Why `many: false`](#why-many-false)
@@ -76,6 +70,10 @@ Here `Serializers::Meta` serializes `meta` of every response. It receives
76
70
  the record or the whole list, and can add any attributes: constants and
77
71
  values from the [context](context.md).
78
72
 
73
+ `Meta` is your class, so it holds only the fields your API sends. `version`
74
+ and `request_id` below are examples: drop them to keep an existing `meta`
75
+ unchanged, and add [paging](#paging) when lists need it.
76
+
79
77
  ```ruby
80
78
  module Serializers
81
79
  # Meta of every response; receives the record or the whole list
@@ -141,110 +139,11 @@ USERS_SERIALIZER.to_json(users, context: {request_id: "f3a9"})
141
139
  serializes the whole list as one response, `{data:, meta:}`, not an Array of
142
140
  responses. See [Why `many: false`](#why-many-false).
143
141
 
144
- ## ActiveRecord
145
-
146
- ### Preloads instead of `includes`
147
-
148
- `plugin :activerecord_preloads` with `config.auto_preload = true` preloads the
149
- relations of the serialized fields, so the query needs no `includes` or
150
- `preload`: the serializer knows which relations the client requested.
151
-
152
- ```ruby
153
- module Serializers
154
- class Base < Serega
155
- plugin :activerecord_preloads
156
- config.auto_preload = true
157
- config.hide_by_default = :auto
158
- end
159
-
160
- class Post < Base
161
- attribute :id
162
- attribute :title
163
- end
164
-
165
- class User < Base
166
- attribute :id
167
- attribute :name
168
- attribute :posts, serializer: Post, many: true # preloads :posts
169
- end
170
- end
171
-
172
- users = User.order(:id).limit(20)
173
- USERS_SERIALIZER.to_json(users)
174
- # SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 20
175
- # => {"data":[{"id":1,"name":"Felonious Gru"}],"meta":{"version":"1"}}
176
-
177
- USERS_SERIALIZER.to_json(users, with: "data(posts)") # users are loaded already
178
- # SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, ...)
179
- # => {"data":[{"id":1,"name":"Felonious Gru","posts":[{"id":1,"title":"Freedonia"}]}],"meta":{"version":"1"}}
180
- ```
181
-
182
- `posts` has a preload, so `hide_by_default = :auto` hides it until a client
183
- requests it. With `includes(:posts)` in the query, the first call loads the
184
- posts it doesn't serialize. See [Preloads](preloads.md).
185
-
186
- ### Batch loading from a cache
187
-
188
- A value that is not a relation, for example a value in a cache, loads with a
189
- [batch loader](batch-loading.md): one cache read for all users, not one per
190
- user.
191
-
192
- ```ruby
193
- module Serializers
194
- class User < Base
195
- # One read_multi for all users; returns {user_id => value}
196
- batch :last_seen_at, lambda { |users|
197
- keys = users.to_h { |user| ["users/#{user.id}/last_seen_at", user.id] }
198
- Rails.cache.read_multi(*keys.keys).transform_keys(keys)
199
- }
200
-
201
- attribute :id
202
- attribute :name
203
- attribute :last_seen_at, batch: true
204
- end
205
- end
206
- ```
207
-
208
- `last_seen_at` has a batch loader, so it is hidden too:
209
- `with: "data(last_seen_at)"` requests it, and only then the cache is read.
210
- `Rails.cache` stands for any ActiveSupport cache store; other caches need a
211
- multi-get, such as Redis `MGET`.
212
-
213
- ### Paging with Kaminari
214
-
215
- `Paging` serializes the Kaminari methods of a scope. `Meta` adds it only for
216
- a scope paged with Kaminari: `.page` on a relation or
217
- `Kaminari.paginate_array`. A record, an Array or a scope without `.page` skip
218
- it, see [Conditional Attributes](conditional-attributes.md).
219
-
220
- ```ruby
221
- module Serializers
222
- class Paging < Base
223
- attribute :page, method: :current_page
224
- attribute :per_page, method: :limit_value
225
- attribute :total_count
226
- attribute :total_pages
227
- end
228
-
229
- class Meta < Base
230
- attribute :version, const: "1"
231
- attribute :request_id, value: proc { |_object, ctx| ctx[:request_id] }, unless_value: :nil?
232
-
233
- attribute :paging, serializer: Paging, method: :itself, many: false, # the scope as one object
234
- if: proc { |object| object.is_a?(Kaminari::PageScopeMethods) } # only Kaminari scopes
235
- end
236
- end
237
-
238
- users = User.order(:id).page(1).per(20)
239
- USERS_SERIALIZER.to_json(users, only: "meta")
240
- # => {"meta":{"version":"1","paging":{"page":1,"per_page":20,"total_count":1,"total_pages":1}}}
241
- ```
242
-
243
- ## Without ActiveRecord
142
+ ## Loading values in batches
244
143
 
245
- Records from an HTTP API, Sequel, ROM or plain Ruby objects work the same way.
246
- Load the values they don't hold with a [batch loader](batch-loading.md): one
247
- request for all users, not one per user.
144
+ Values the records don't hold load with a [batch loader](batch-loading.md):
145
+ one request for all users, not one per user. Here the users come from an HTTP
146
+ API.
248
147
 
249
148
  ```ruby
250
149
  User = Data.define(:id, :name) # for example, parsed from an HTTP API
@@ -267,9 +166,14 @@ USERS_SERIALIZER.to_json(users, with: "data(avatar_url)")
267
166
  `avatar_url` has a batch loader, so the service is called only when a client
268
167
  requests the field.
269
168
 
270
- Without `.page` on the records, paging comes from the
271
- [context](context.md), for example a Pagy object or a Hash built from the API
272
- response:
169
+ With ActiveRecord, relations load with preloads, not `includes`: see
170
+ [Preloads instead of `includes`](responses-rails.md#preloads-instead-of-includes).
171
+
172
+ ## Paging
173
+
174
+ Here paging comes from the [context](context.md), for example a Hash built
175
+ from the API response or a Pagy object. With Kaminari, see
176
+ [Paging with Kaminari](responses-rails.md#paging-with-kaminari).
273
177
 
274
178
  ```ruby
275
179
  module Serializers
@@ -293,170 +197,6 @@ USERS_SERIALIZER.to_json(users, context: {paging: {page: 1, per_page: 20, total_
293
197
  Records loaded as Hashes read their keys with `hash_access`, see
294
198
  [Hash Records](hash-records.md).
295
199
 
296
- ## Rails
297
-
298
- ### Controllers
299
-
300
- In this example, controllers keep the response serializers in constants and
301
- render JSON with `json`, an `ApplicationController` method that adds the
302
- [common context](#a-common-context):
303
-
304
- ```ruby
305
- class UsersController < ApplicationController
306
- USER_SERIALIZER = Serializers::Response.one(Serializers::User)
307
- USERS_SERIALIZER = Serializers::Response.list(Serializers::User)
308
-
309
- def index
310
- users = User.order(:id).page(params[:page]).per(20)
311
- render json: json(USERS_SERIALIZER, users)
312
- end
313
-
314
- def show
315
- user = User.find(params[:id])
316
- render json: json(USER_SERIALIZER, user)
317
- end
318
- end
319
- ```
320
-
321
- ### A common context
322
-
323
- Most responses need the same [context](context.md): the current user, the
324
- request id. This example builds it in one method of `ApplicationController`,
325
- as a serializer has no access to the request. `json` serializes with it, and
326
- with the fields the request [selects](#selecting-fields) in its `only`,
327
- `with`, `except` and `preset` parameters:
328
-
329
- ```ruby
330
- class ApplicationController < ActionController::API
331
- rescue_from Serega::AttributeNotExist, Serega::PresetNotExist do |error|
332
- render json: {errors: [{source: "fields", title: error.message}]}, status: :bad_request
333
- end
334
-
335
- private
336
-
337
- # The context of every response
338
- def serialization_context
339
- {
340
- request_id: request.request_id,
341
- current_user: proc { current_user } # found only when a serialized field reads it
342
- }
343
- end
344
-
345
- # JSON of the serializer with the fields of the request and the common
346
- # context; `context:` adds to it
347
- def json(serializer, object, context: {})
348
- serializer.to_json(
349
- object,
350
- only: params[:only],
351
- with: params[:with],
352
- except: params[:except],
353
- preset: params[:preset],
354
- context: serialization_context.merge(context)
355
- )
356
- end
357
- end
358
- ```
359
-
360
- `current_user: current_user` works too, but it finds the user for every
361
- response. With a proc, a response finds the user only when a requested field
362
- reads it, so a public response with no user-specific fields skips the lookup:
363
-
364
- ```ruby
365
- module Serializers
366
- class User < Base
367
- attribute :id
368
- attribute :name
369
- attribute :editable, hide: true, value: proc { |user, ctx| user == ctx[:current_user].call }
370
- end
371
- end
372
-
373
- ```
374
-
375
- ```text
376
- GET /users
377
- {"data":[{"id":1,"name":"Felonious Gru"},{"id":2,"name":"Lucy"}],"meta":{"version":"1","request_id":"f3a9"}}
378
- The proc is not called, so the user is not found.
379
-
380
- GET /users?with=data(editable)
381
- {"data":[{"id":1,"name":"Felonious Gru","editable":true},{"id":2,"name":"Lucy","editable":false}],
382
- "meta":{"version":"1","request_id":"f3a9"}}
383
-
384
- GET /users?only=data(nickname)
385
- 400 {"errors":[{"source":"fields","title":"Not existing attributes: data(nickname)"}]}
386
- ```
387
-
388
- A `:value` proc runs once per object, so the proc runs once per user. Rails
389
- apps usually memoize `current_user`, which keeps the lookup to one query; a
390
- [batch loader](batch-loading.md#values-for-the-current-user) calls the proc
391
- once per serialization. Where there is no request, as in a mailer, pass
392
- `current_user: proc {}`, and the same serializers work.
393
-
394
- ### Flash messages
395
-
396
- `notice` and `alert`, the names of Rails flash messages, can go to `meta` the
397
- same way as `request_id`: pass them in the context, and add them to `Meta`.
398
-
399
- ```ruby
400
- attribute :notice, value: proc { |_object, ctx| ctx[:notice] }, unless_value: :nil?
401
- attribute :alert, value: proc { |_object, ctx| ctx[:alert] }, unless_value: :nil?
402
- ```
403
-
404
- API-only apps have no flash, so the controller adds the messages itself:
405
- `json(USERS_SERIALIZER, users, context: {notice: "Users imported"})`. Other
406
- apps add them to `serialization_context`:
407
- `notice: flash[:notice], alert: flash[:alert]`.
408
-
409
- ### Validation errors
410
-
411
- This example renders validation errors as `{errors: [...]}`; give them the
412
- shape your API uses. `ActiveModel::Errors#objects` returns
413
- `ActiveModel::Error` objects, so a serializer reads them like any records.
414
- Error serializers inherit `Serega` directly: they need none of the config and
415
- plugins of `Base`.
416
-
417
- ```ruby
418
- module Serializers
419
- class Error < Serega
420
- attribute :source, method: :attribute
421
- attribute :title, method: :message
422
- end
423
-
424
- # The errors of one record as one response
425
- class Errors < Serega
426
- config.many = false # one {errors:}, not one response per error
427
- attribute :errors, serializer: Error, method: :objects, many: true # ActiveModel::Error objects
428
- end
429
- end
430
- ```
431
-
432
- `create!` and `update!` raise `ActiveRecord::RecordInvalid` for an invalid
433
- record. Here actions don't check for errors, and one handler in
434
- `ApplicationController` renders the errors of every action:
435
-
436
- ```ruby
437
- class ApplicationController < ActionController::API
438
- rescue_from ActiveRecord::RecordInvalid do |error|
439
- errors = error.record.errors
440
- render json: Serializers::Errors.to_json(errors), status: :unprocessable_entity
441
- end
442
- end
443
-
444
- class UsersController < ApplicationController
445
- def create
446
- user = User.create!(user_params) # raises ActiveRecord::RecordInvalid for an invalid user
447
- render json: json(USER_SERIALIZER, user), status: :created
448
- end
449
- end
450
- ```
451
-
452
- ```text
453
- POST /users {"user":{"name":""}}
454
- 422 {"errors":[{"source":"name","title":"can't be blank"}]}
455
- ```
456
-
457
- A serializer named `Serializers::User` lives in a file that your autoloader
458
- maps to that name, for example `app/serializers/serializers/user.rb`.
459
-
460
200
  ## Fields serialized by default
461
201
 
462
202
  `config.hide_by_default` chooses what a response serializes when the client
@@ -494,10 +234,9 @@ module Serializers
494
234
  attribute :posts, serializer: Post, many: true
495
235
  end
496
236
 
497
- # Report serializers share their own config, apart from Base
498
- class ReportBase < Serega
499
- plugin :activerecord_preloads
500
- config.auto_preload = true
237
+ # Export serializers share their own config, apart from Base
238
+ class ExportBase < Serega
239
+ config.hide_by_default = true # every export names its fields
501
240
  end
502
241
  end
503
242
  ```
@@ -513,18 +252,24 @@ the whole list as one object, thus:
513
252
 
514
253
  - `config.many = false` in `Response` builds one response from the list, not
515
254
  one per user. A `many:` option of a call overrides it;
516
- - `many: false` on `meta` and `paging` passes the list as one object, so
517
- `Paging` can call `current_page` and the other Kaminari methods;
255
+ - `many: false` on `meta` passes the list as one object, so `Meta` reads the
256
+ whole list, for example its paging;
518
257
  - `many: true` on `data` serializes each user.
519
258
 
520
- Without `many: false` on `paging`, Serega calls the methods of `Paging` on
521
- each user and raises
522
- `NoMethodError: undefined method 'current_page' for an instance of User`.
523
-
524
259
  ## Selecting fields
525
260
 
526
- Clients select fields from the root of the response. `meta` is left out
527
- unless the selection names it:
261
+ Clients can request any field of the response: `data`, `meta`, or any
262
+ fields inside them. The API passes their selection to the response
263
+ serializer unchanged, as the [`json` helper](responses-rails.md#a-common-context) does.
264
+
265
+ ```text
266
+ GET /users?only=data(id,name)
267
+ GET /users?only=meta(paging(total_count))
268
+ GET /users?only=data(id),meta
269
+ GET /users?with=data(posts(comments_count))
270
+ ```
271
+
272
+ `meta` is left out unless the selection names it:
528
273
 
529
274
  ```ruby
530
275
  USERS_SERIALIZER.to_json(users, only: "data(id,name),meta")
@@ -537,8 +282,8 @@ USERS_SERIALIZER.to_json(users, only: "data(id),meta(paging(total_count))")
537
282
  # => {"data":[{"id":1}],"meta":{"paging":{"total_count":1}}}
538
283
  ```
539
284
 
540
- When `?fields=` names the fields of the records, nest them under `data`. An
541
- Array of names works; a String inside a Hash is not parsed:
285
+ To keep an existing `?fields=id,name` parameter that names the fields of the
286
+ records, nest its names under `data`:
542
287
 
543
288
  ```ruby
544
289
  fields = params[:fields]&.split(",") # ?fields=id,name
@@ -111,6 +111,13 @@ UserSerializer.to_h(gru, only: "username,friends(username,email)")
111
111
  UserSerializer.to_h(users, only: params[:fields]) # all default fields when params[:fields] is nil
112
112
  ```
113
113
 
114
+ Public APIs select fields from the root of the response the same way, also
115
+ inside a list wrapper: Google APIs with
116
+ [`fields=items(id,snippet(title))`](https://developers.google.com/youtube/v3/getting-started),
117
+ Stripe with [`expand[]=data.customer`](https://docs.stripe.com/expand) and
118
+ Mailchimp with
119
+ [`fields=lists.name,lists.id`](https://mailchimp.com/developer/marketing/docs/methods-parameters/).
120
+
114
121
  ## Unknown fields
115
122
 
116
123
  An unknown field raises `Serega::AttributeNotExist`. Its `#serializer` and
@@ -2,6 +2,10 @@
2
2
 
3
3
  class Serega
4
4
  module SeregaPlugins
5
+ # Deprecated: a response serializer with `data` and `meta` attributes
6
+ # replaces it, see `docs/responses.md` in the gem or
7
+ # [Response Serializers](https://github.com/andreyruby/serega/blob/master/docs/responses.md).
8
+ #
5
9
  # `plugin :context_metadata` adds metadata given per serialization with
6
10
  # the `:meta` option. Load `plugin :root` first.
7
11
  #
@@ -2,6 +2,10 @@
2
2
 
3
3
  class Serega
4
4
  module SeregaPlugins
5
+ # Deprecated: a response serializer with `data` and `meta` attributes
6
+ # replaces it, see `docs/responses.md` in the gem or
7
+ # [Response Serializers](https://github.com/andreyruby/serega/blob/master/docs/responses.md).
8
+ #
5
9
  # `plugin :metadata` adds metadata defined with
6
10
  # Serega::SeregaPlugins::Metadata::ClassMethods#meta_attribute. Load
7
11
  # `plugin :root` first.
@@ -2,6 +2,10 @@
2
2
 
3
3
  class Serega
4
4
  module SeregaPlugins
5
+ # Deprecated: a response serializer with `data` and `meta` attributes
6
+ # replaces it, see `docs/responses.md` in the gem or
7
+ # [Response Serializers](https://github.com/andreyruby/serega/blob/master/docs/responses.md).
8
+ #
5
9
  # `plugin :root` wraps results in a root key, `:data` by default
6
10
  #
7
11
  # ```ruby
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: serega
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.52.0
4
+ version: 0.52.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andrey
@@ -39,6 +39,7 @@ files:
39
39
  - docs/presets.md
40
40
  - docs/ractors.md
41
41
  - docs/relations.md
42
+ - docs/responses-rails.md
42
43
  - docs/responses.md
43
44
  - docs/root-and-metadata.md
44
45
  - docs/selecting-fields.md