serega 0.51.1 → 0.52.0

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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +48 -21
  3. data/VERSION +1 -1
  4. data/docs/README.md +41 -0
  5. data/docs/attributes.md +248 -0
  6. data/docs/batch-loading.md +207 -0
  7. data/docs/camel-case.md +86 -0
  8. data/docs/conditional-attributes.md +165 -0
  9. data/docs/configuration.md +47 -0
  10. data/docs/context.md +34 -0
  11. data/docs/errors.md +38 -0
  12. data/docs/formatters.md +231 -0
  13. data/docs/hash-records.md +93 -0
  14. data/docs/migrating-from-root-and-metadata.md +50 -0
  15. data/docs/preloads.md +125 -0
  16. data/docs/prepare-initial-objects.md +72 -0
  17. data/docs/presenter.md +87 -0
  18. data/docs/presets.md +174 -0
  19. data/docs/ractors.md +54 -0
  20. data/docs/relations.md +233 -0
  21. data/docs/responses.md +548 -0
  22. data/docs/root-and-metadata.md +110 -0
  23. data/docs/selecting-fields.md +157 -0
  24. data/docs/serializing.md +113 -0
  25. data/docs/testing.md +230 -0
  26. data/lib/serega/attribute_normalizer.rb +26 -8
  27. data/lib/serega/attribute_normalizers/block.rb +3 -3
  28. data/lib/serega/config.rb +28 -13
  29. data/lib/serega/errors.rb +2 -2
  30. data/lib/serega/plan/cache.rb +13 -29
  31. data/lib/serega/plan/per_ractor_cache.rb +2 -2
  32. data/lib/serega/plan/point.rb +13 -2
  33. data/lib/serega/plan.rb +1 -1
  34. data/lib/serega/plugins/context_metadata/context_metadata.rb +1 -1
  35. data/lib/serega/plugins/root/root.rb +10 -10
  36. data/lib/serega/plugins.rb +13 -0
  37. data/lib/serega/result_code/relation_point_code.rb +3 -2
  38. data/lib/serega/source_group.rb +1 -1
  39. data/lib/serega/validations/attribute/check_block.rb +4 -7
  40. data/lib/serega/validations/attribute/check_opt_hash_access.rb +2 -3
  41. data/lib/serega/validations/check_batch_loader_params.rb +2 -1
  42. data/lib/serega.rb +30 -26
  43. data/sig/serega.rbs +10 -8
  44. metadata +23 -1
data/docs/responses.md ADDED
@@ -0,0 +1,548 @@
1
+ # Response Serializers
2
+
3
+ In this guide, a response serializer wraps the records of an API response
4
+ with `data` and adds `meta`, such as paging. It is a plain serializer with a
5
+ `data` and a `meta` attribute, so it uses the attribute options you already
6
+ know, and clients select its fields from the root.
7
+
8
+ ```json
9
+ {
10
+ "data": [{"id": 1, "name": "Felonious Gru"}],
11
+ "meta": {"version": "1", "paging": {"page": 1, "per_page": 20, "total_count": 1, "total_pages": 1}}
12
+ }
13
+ ```
14
+
15
+ This guide is an example: one of many ways to structure API responses. Take
16
+ the parts that fit your API and change the rest.
17
+
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.
21
+
22
+ Response serializers replace the [root and metadata plugins](root-and-metadata.md),
23
+ see [Migrating from the Root and Metadata Plugins](migrating-from-root-and-metadata.md).
24
+
25
+ ## Table of Contents
26
+
27
+ <!-- toc -->
28
+
29
+ - [Step by step](#step-by-step)
30
+ - [1. Serialize the records](#1-serialize-the-records)
31
+ - [2. Describe `meta`](#2-describe-meta)
32
+ - [3. Add a common response shape](#3-add-a-common-response-shape)
33
+ - [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)
44
+ - [Fields serialized by default](#fields-serialized-by-default)
45
+ - [Another mode for some serializers](#another-mode-for-some-serializers)
46
+ - [Why `many: false`](#why-many-false)
47
+ - [Selecting fields](#selecting-fields)
48
+
49
+ <!-- tocstop -->
50
+
51
+ ## Step by step
52
+
53
+ ### 1. Serialize the records
54
+
55
+ ```ruby
56
+ module Serializers
57
+ class Base < Serega
58
+ config.hide_by_default = :auto # relations and batches only on request
59
+ end
60
+
61
+ class User < Base
62
+ attribute :id
63
+ attribute :name
64
+ end
65
+ end
66
+ ```
67
+
68
+ With `hide_by_default = :auto`, attributes that load more data are serialized
69
+ only when the client requests them. The default, `false`, serializes every
70
+ attribute and hides nothing. See
71
+ [Fields serialized by default](#fields-serialized-by-default).
72
+
73
+ ### 2. Describe `meta`
74
+
75
+ Here `Serializers::Meta` serializes `meta` of every response. It receives
76
+ the record or the whole list, and can add any attributes: constants and
77
+ values from the [context](context.md).
78
+
79
+ ```ruby
80
+ module Serializers
81
+ # Meta of every response; receives the record or the whole list
82
+ class Meta < Base
83
+ attribute :version, const: "1"
84
+ attribute :request_id, value: proc { |_object, ctx| ctx[:request_id] }, unless_value: :nil?
85
+ end
86
+ end
87
+ ```
88
+
89
+ ### 3. Add a common response shape
90
+
91
+ `Serializers::Response` gives every response the same shape, `data` and
92
+ `meta`, often called a response envelope, so you don't write a `Show` and an
93
+ `Index` serializer for each resource. It is not part of Serega: it is a plain
94
+ Ruby technique that skips this boilerplate. It is your code, so change it as
95
+ your API needs, for example add `links` or `errors`, or make `meta` optional.
96
+
97
+ ```ruby
98
+ module Serializers
99
+ # Response serializers of one shape: the records under `data`, and `meta`
100
+ # from a serializer that receives them too
101
+ module Response
102
+ # One record under `data`
103
+ def self.one(serializer, meta: Meta)
104
+ Class.new(Base) do
105
+ config.many = false # one {data:, meta:}, not [{data:, meta:}, {data:, meta:}, ...]
106
+ attribute :data, serializer: serializer, method: :itself # Ruby's Object#itself
107
+ attribute :meta, serializer: meta, method: :itself
108
+ end
109
+ end
110
+
111
+ # A list under `data`; the `meta` serializer receives the whole list
112
+ def self.list(serializer, meta: Meta)
113
+ Class.new(Base) do
114
+ config.many = false # one {data:, meta:}, not [{data:, meta:}, {data:, meta:}, ...]
115
+ attribute :data, serializer: serializer, method: :itself, many: true # Ruby's Object#itself
116
+ attribute :meta, serializer: meta, method: :itself, many: false # the list as one object
117
+ end
118
+ end
119
+ end
120
+ end
121
+ ```
122
+
123
+ ### 4. Serialize responses
124
+
125
+ ```ruby
126
+ USER_SERIALIZER = Serializers::Response.one(Serializers::User)
127
+ USERS_SERIALIZER = Serializers::Response.list(Serializers::User)
128
+
129
+ USER_SERIALIZER.to_json(user)
130
+ # => {"data":{"id":1,"name":"Felonious Gru"},"meta":{"version":"1"}}
131
+
132
+ USERS_SERIALIZER.to_json(users, context: {request_id: "f3a9"})
133
+ # => {"data":[{"id":1,"name":"Felonious Gru"}],"meta":{"version":"1","request_id":"f3a9"}}
134
+ ```
135
+
136
+ - Build response serializers once, in constants. Each `one` or `list` call
137
+ builds a new class with its own [plan cache](serializing.md#plan-cache),
138
+ thus a call per request builds the class and its plans again.
139
+ - A constant names the class, so errors show `USERS_SERIALIZER`.
140
+ - `Response.one` and `Response.list` set `config.many = false`, so a call
141
+ serializes the whole list as one response, `{data:, meta:}`, not an Array of
142
+ responses. See [Why `many: false`](#why-many-false).
143
+
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
244
+
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.
248
+
249
+ ```ruby
250
+ User = Data.define(:id, :name) # for example, parsed from an HTTP API
251
+
252
+ module Serializers
253
+ class User < Base
254
+ # One request for all users; returns {user_id => url}
255
+ batch :avatar_url, ->(users) { AvatarService.urls(users.map(&:id)) }
256
+
257
+ attribute :id
258
+ attribute :name
259
+ attribute :avatar_url, batch: true
260
+ end
261
+ end
262
+
263
+ USERS_SERIALIZER.to_json(users, with: "data(avatar_url)")
264
+ # => {"data":[{"id":1,"name":"Felonious Gru","avatar_url":"https://..."}],"meta":{"version":"1"}}
265
+ ```
266
+
267
+ `avatar_url` has a batch loader, so the service is called only when a client
268
+ requests the field.
269
+
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:
273
+
274
+ ```ruby
275
+ module Serializers
276
+ class Paging < Base
277
+ attribute :page, hash_access: true
278
+ attribute :per_page, hash_access: true
279
+ attribute :total_count, hash_access: true
280
+ end
281
+
282
+ class Meta < Base
283
+ attribute :version, const: "1"
284
+ attribute :request_id, value: proc { |_object, ctx| ctx[:request_id] }, unless_value: :nil?
285
+ attribute :paging, serializer: Paging, value: proc { |_object, ctx| ctx[:paging] }, unless_value: :nil?
286
+ end
287
+ end
288
+
289
+ USERS_SERIALIZER.to_json(users, context: {paging: {page: 1, per_page: 20, total_count: 1}})
290
+ # => {"data":[...],"meta":{"version":"1","paging":{"page":1,"per_page":20,"total_count":1}}}
291
+ ```
292
+
293
+ Records loaded as Hashes read their keys with `hash_access`, see
294
+ [Hash Records](hash-records.md).
295
+
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
+ ## Fields serialized by default
461
+
462
+ `config.hide_by_default` chooses what a response serializes when the client
463
+ names no fields. Each mode fits its own case:
464
+
465
+ - `false`, the default: every attribute. Fits small serializers and internal
466
+ APIs, where a response is the whole record.
467
+ - `true`: no attribute, unless it has `hide: false`. Every call names its
468
+ fields with `only:` or `with:`, which fits mailers, exports and APIs whose
469
+ clients always choose fields. The `data` and `meta` attributes of
470
+ `Response` then need `hide: false` to stay in the response.
471
+ - `:auto`: every attribute except those with a preload or a batch loader:
472
+ relations preloaded with `auto_preload`, and batch-loaded values. A response
473
+ runs no extra query until a client requests such a field. Fits APIs whose
474
+ responses have relations or costly fields.
475
+
476
+ A plain relation without a preload stays visible with `:auto`, and so do
477
+ `data`, `meta` and `paging`: `method: :itself` is never preloaded. See
478
+ [Hiding by default](selecting-fields.md#hiding-by-default).
479
+
480
+ ### Another mode for some serializers
481
+
482
+ `Base` is a convention, not a requirement: the mode belongs to each
483
+ serializer. A serializer can change it, inherit another base serializer, or
484
+ inherit `Serega` directly with its own config. For example, a dashboard that
485
+ always shows its relations:
486
+
487
+ ```ruby
488
+ module Serializers
489
+ # Relations of the dashboard are serialized by default
490
+ class Dashboard < Base
491
+ config.hide_by_default = false
492
+
493
+ attribute :name
494
+ attribute :posts, serializer: Post, many: true
495
+ end
496
+
497
+ # Report serializers share their own config, apart from Base
498
+ class ReportBase < Serega
499
+ plugin :activerecord_preloads
500
+ config.auto_preload = true
501
+ end
502
+ end
503
+ ```
504
+
505
+ A serializer reads the mode when it defines an attribute, so a change affects
506
+ the attributes defined after it. Attributes inherited from the parent keep the
507
+ parent's mode. Related serializers follow their own config.
508
+
509
+ ## Why `many: false`
510
+
511
+ Serega serializes a scope or an Array as a list. A response serializer gets
512
+ the whole list as one object, thus:
513
+
514
+ - `config.many = false` in `Response` builds one response from the list, not
515
+ 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;
518
+ - `many: true` on `data` serializes each user.
519
+
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
+ ## Selecting fields
525
+
526
+ Clients select fields from the root of the response. `meta` is left out
527
+ unless the selection names it:
528
+
529
+ ```ruby
530
+ USERS_SERIALIZER.to_json(users, only: "data(id,name),meta")
531
+ # => {"data":[{"id":1,"name":"Felonious Gru"}],"meta":{"version":"1","paging":{...}}}
532
+
533
+ USERS_SERIALIZER.to_json(users, only: "data(id)")
534
+ # => {"data":[{"id":1}]}
535
+
536
+ USERS_SERIALIZER.to_json(users, only: "data(id),meta(paging(total_count))")
537
+ # => {"data":[{"id":1}],"meta":{"paging":{"total_count":1}}}
538
+ ```
539
+
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:
542
+
543
+ ```ruby
544
+ fields = params[:fields]&.split(",") # ?fields=id,name
545
+ USERS_SERIALIZER.to_json(users, only: fields && {data: fields, meta: nil})
546
+ ```
547
+
548
+ See [Selecting Fields](selecting-fields.md).
@@ -0,0 +1,110 @@
1
+ # Root Key and Metadata
2
+
3
+ > **Deprecated.** Use [response serializers](responses.md) instead: a
4
+ > serializer with `data` and `meta` attributes. They use the attribute options
5
+ > you already know, clients select their fields from the root, and they don't
6
+ > depend on plugin options. See
7
+ > [Migrating from the Root and Metadata Plugins](migrating-from-root-and-metadata.md).
8
+ >
9
+ > Loading `plugin :root`, `plugin :metadata` or `plugin :context_metadata`
10
+ > prints a warning with the file and line. To hide it, set
11
+ > `config.deprecation_warnings = false` before the `plugin` call, or once on
12
+ > `Serega` itself before the serializers load.
13
+
14
+ ## Table of Contents
15
+
16
+ <!-- toc -->
17
+
18
+ - [Root key](#root-key)
19
+ - [Metadata](#metadata)
20
+ - [Metadata per serialization](#metadata-per-serialization)
21
+
22
+ <!-- tocstop -->
23
+
24
+ ## Root key
25
+
26
+ `plugin :root` wraps results in a root key, `:data` by default.
27
+
28
+ ```ruby
29
+ class UserSerializer < Serega
30
+ plugin :root
31
+ attribute :username
32
+ end
33
+
34
+ UserSerializer.to_h(user) # => {data: {username: "gru"}}
35
+ UserSerializer.to_h([user]) # => {data: [{username: "gru"}]}
36
+ ```
37
+
38
+ Other keys:
39
+
40
+ ```ruby
41
+ plugin :root, root: :users # one key for objects and lists
42
+ plugin :root, root_one: :user, root_many: :users # separate keys
43
+ plugin :root, root: nil # no root unless given per serialization
44
+ ```
45
+
46
+ Per serialization:
47
+
48
+ ```ruby
49
+ UserSerializer.to_h(user, root: :user) # => {user: {username: "gru"}}
50
+ UserSerializer.to_h(user, root: nil) # => {username: "gru"}
51
+ ```
52
+
53
+ `config.root.one` and `config.root.many` read and change the keys in child
54
+ serializers.
55
+
56
+ `.to_struct` and `.to_data` return a Hash with `Struct` or `Data` objects
57
+ under the root key:
58
+
59
+ ```ruby
60
+ UserSerializer.to_struct(user) # => {data: #<struct username="gru">}
61
+ ```
62
+
63
+ ## Metadata
64
+
65
+ `plugin :metadata` adds metadata defined with `meta_attribute` next to the
66
+ [root key](#root-key). Load `plugin :root` first.
67
+
68
+ ```ruby
69
+ class AppSerializer < Serega
70
+ plugin :root
71
+ plugin :metadata
72
+
73
+ meta_attribute :version, const: "1.2.3"
74
+ meta_attribute :meta, :paging, hide_nil: true do |records, ctx|
75
+ next unless records.respond_to?(:total_count)
76
+
77
+ {page: records.current_page, total_count: records.total_count}
78
+ end
79
+ end
80
+
81
+ UserSerializer.to_h(users.page(1))
82
+ # => {data: [...], version: "1.2.3", meta: {paging: {page: 1, total_count: 120}}}
83
+ ```
84
+
85
+ `meta_attribute` accepts:
86
+
87
+ - a path of keys: `:meta, :paging` builds `{meta: {paging: value}}`;
88
+ - the value: `const:`, `value:` with a callable, or a block. Callables receive
89
+ the serialized objects and the [context](context.md);
90
+ - `hide_nil: true` to skip `nil` values, `hide_empty: true` to skip `nil` and
91
+ empty values.
92
+
93
+ ## Metadata per serialization
94
+
95
+ `plugin :context_metadata` adds metadata given per serialization with the
96
+ `:meta` option. Load `plugin :root` first.
97
+
98
+ ```ruby
99
+ class AppSerializer < Serega
100
+ plugin :root
101
+ plugin :context_metadata
102
+ end
103
+
104
+ UserSerializer.to_h(user, meta: {version: "1.0.1"})
105
+ # => {data: {username: "gru"}, version: "1.0.1"}
106
+ ```
107
+
108
+ `plugin :context_metadata, context_metadata_key: :extra` or
109
+ `config.context_metadata.key = :extra` changes the option name. The previous
110
+ name raises `Serega::SeregaError`.