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.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +49 -21
  3. data/VERSION +1 -1
  4. data/docs/README.md +42 -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 +262 -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-rails.md +287 -0
  22. data/docs/responses.md +293 -0
  23. data/docs/root-and-metadata.md +110 -0
  24. data/docs/selecting-fields.md +164 -0
  25. data/docs/serializing.md +113 -0
  26. data/docs/testing.md +230 -0
  27. data/lib/serega/attribute_normalizer.rb +26 -8
  28. data/lib/serega/attribute_normalizers/block.rb +3 -3
  29. data/lib/serega/config.rb +28 -13
  30. data/lib/serega/errors.rb +2 -2
  31. data/lib/serega/plan/cache.rb +13 -29
  32. data/lib/serega/plan/per_ractor_cache.rb +2 -2
  33. data/lib/serega/plan/point.rb +13 -2
  34. data/lib/serega/plan.rb +1 -1
  35. data/lib/serega/plugins/context_metadata/context_metadata.rb +5 -1
  36. data/lib/serega/plugins/metadata/metadata.rb +4 -0
  37. data/lib/serega/plugins/root/root.rb +14 -10
  38. data/lib/serega/plugins.rb +13 -0
  39. data/lib/serega/result_code/relation_point_code.rb +3 -2
  40. data/lib/serega/source_group.rb +1 -1
  41. data/lib/serega/validations/attribute/check_block.rb +4 -7
  42. data/lib/serega/validations/attribute/check_opt_hash_access.rb +2 -3
  43. data/lib/serega/validations/check_batch_loader_params.rb +2 -1
  44. data/lib/serega.rb +30 -26
  45. data/sig/serega.rbs +10 -8
  46. metadata +24 -1
data/docs/responses.md ADDED
@@ -0,0 +1,293 @@
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, for example
7
+ `?only=data(id,name)` (see [Selecting fields](#selecting-fields)).
8
+
9
+ ```json
10
+ {
11
+ "data": [{"id": 1, "name": "Felonious Gru"}],
12
+ "meta": {"version": "1", "paging": {"page": 1, "per_page": 20, "total_count": 1, "total_pages": 1}}
13
+ }
14
+ ```
15
+
16
+ This guide is an example: one of many ways to structure API responses. Take
17
+ the parts that fit your API and change the rest.
18
+
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.
23
+
24
+ Response serializers replace the [root and metadata plugins](root-and-metadata.md),
25
+ see [Migrating from the Root and Metadata Plugins](migrating-from-root-and-metadata.md).
26
+
27
+ ## Table of Contents
28
+
29
+ <!-- toc -->
30
+
31
+ - [Step by step](#step-by-step)
32
+ - [1. Serialize the records](#1-serialize-the-records)
33
+ - [2. Describe `meta`](#2-describe-meta)
34
+ - [3. Add a common response shape](#3-add-a-common-response-shape)
35
+ - [4. Serialize responses](#4-serialize-responses)
36
+ - [Loading values in batches](#loading-values-in-batches)
37
+ - [Paging](#paging)
38
+ - [Fields serialized by default](#fields-serialized-by-default)
39
+ - [Another mode for some serializers](#another-mode-for-some-serializers)
40
+ - [Why `many: false`](#why-many-false)
41
+ - [Selecting fields](#selecting-fields)
42
+
43
+ <!-- tocstop -->
44
+
45
+ ## Step by step
46
+
47
+ ### 1. Serialize the records
48
+
49
+ ```ruby
50
+ module Serializers
51
+ class Base < Serega
52
+ config.hide_by_default = :auto # relations and batches only on request
53
+ end
54
+
55
+ class User < Base
56
+ attribute :id
57
+ attribute :name
58
+ end
59
+ end
60
+ ```
61
+
62
+ With `hide_by_default = :auto`, attributes that load more data are serialized
63
+ only when the client requests them. The default, `false`, serializes every
64
+ attribute and hides nothing. See
65
+ [Fields serialized by default](#fields-serialized-by-default).
66
+
67
+ ### 2. Describe `meta`
68
+
69
+ Here `Serializers::Meta` serializes `meta` of every response. It receives
70
+ the record or the whole list, and can add any attributes: constants and
71
+ values from the [context](context.md).
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
+
77
+ ```ruby
78
+ module Serializers
79
+ # Meta of every response; receives the record or the whole list
80
+ class Meta < Base
81
+ attribute :version, const: "1"
82
+ attribute :request_id, value: proc { |_object, ctx| ctx[:request_id] }, unless_value: :nil?
83
+ end
84
+ end
85
+ ```
86
+
87
+ ### 3. Add a common response shape
88
+
89
+ `Serializers::Response` gives every response the same shape, `data` and
90
+ `meta`, often called a response envelope, so you don't write a `Show` and an
91
+ `Index` serializer for each resource. It is not part of Serega: it is a plain
92
+ Ruby technique that skips this boilerplate. It is your code, so change it as
93
+ your API needs, for example add `links` or `errors`, or make `meta` optional.
94
+
95
+ ```ruby
96
+ module Serializers
97
+ # Response serializers of one shape: the records under `data`, and `meta`
98
+ # from a serializer that receives them too
99
+ module Response
100
+ # One record under `data`
101
+ def self.one(serializer, meta: Meta)
102
+ Class.new(Base) do
103
+ config.many = false # one {data:, meta:}, not [{data:, meta:}, {data:, meta:}, ...]
104
+ attribute :data, serializer: serializer, method: :itself # Ruby's Object#itself
105
+ attribute :meta, serializer: meta, method: :itself
106
+ end
107
+ end
108
+
109
+ # A list under `data`; the `meta` serializer receives the whole list
110
+ def self.list(serializer, meta: Meta)
111
+ Class.new(Base) do
112
+ config.many = false # one {data:, meta:}, not [{data:, meta:}, {data:, meta:}, ...]
113
+ attribute :data, serializer: serializer, method: :itself, many: true # Ruby's Object#itself
114
+ attribute :meta, serializer: meta, method: :itself, many: false # the list as one object
115
+ end
116
+ end
117
+ end
118
+ end
119
+ ```
120
+
121
+ ### 4. Serialize responses
122
+
123
+ ```ruby
124
+ USER_SERIALIZER = Serializers::Response.one(Serializers::User)
125
+ USERS_SERIALIZER = Serializers::Response.list(Serializers::User)
126
+
127
+ USER_SERIALIZER.to_json(user)
128
+ # => {"data":{"id":1,"name":"Felonious Gru"},"meta":{"version":"1"}}
129
+
130
+ USERS_SERIALIZER.to_json(users, context: {request_id: "f3a9"})
131
+ # => {"data":[{"id":1,"name":"Felonious Gru"}],"meta":{"version":"1","request_id":"f3a9"}}
132
+ ```
133
+
134
+ - Build response serializers once, in constants. Each `one` or `list` call
135
+ builds a new class with its own [plan cache](serializing.md#plan-cache),
136
+ thus a call per request builds the class and its plans again.
137
+ - A constant names the class, so errors show `USERS_SERIALIZER`.
138
+ - `Response.one` and `Response.list` set `config.many = false`, so a call
139
+ serializes the whole list as one response, `{data:, meta:}`, not an Array of
140
+ responses. See [Why `many: false`](#why-many-false).
141
+
142
+ ## Loading values in batches
143
+
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.
147
+
148
+ ```ruby
149
+ User = Data.define(:id, :name) # for example, parsed from an HTTP API
150
+
151
+ module Serializers
152
+ class User < Base
153
+ # One request for all users; returns {user_id => url}
154
+ batch :avatar_url, ->(users) { AvatarService.urls(users.map(&:id)) }
155
+
156
+ attribute :id
157
+ attribute :name
158
+ attribute :avatar_url, batch: true
159
+ end
160
+ end
161
+
162
+ USERS_SERIALIZER.to_json(users, with: "data(avatar_url)")
163
+ # => {"data":[{"id":1,"name":"Felonious Gru","avatar_url":"https://..."}],"meta":{"version":"1"}}
164
+ ```
165
+
166
+ `avatar_url` has a batch loader, so the service is called only when a client
167
+ requests the field.
168
+
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).
177
+
178
+ ```ruby
179
+ module Serializers
180
+ class Paging < Base
181
+ attribute :page, hash_access: true
182
+ attribute :per_page, hash_access: true
183
+ attribute :total_count, hash_access: true
184
+ end
185
+
186
+ class Meta < Base
187
+ attribute :version, const: "1"
188
+ attribute :request_id, value: proc { |_object, ctx| ctx[:request_id] }, unless_value: :nil?
189
+ attribute :paging, serializer: Paging, value: proc { |_object, ctx| ctx[:paging] }, unless_value: :nil?
190
+ end
191
+ end
192
+
193
+ USERS_SERIALIZER.to_json(users, context: {paging: {page: 1, per_page: 20, total_count: 1}})
194
+ # => {"data":[...],"meta":{"version":"1","paging":{"page":1,"per_page":20,"total_count":1}}}
195
+ ```
196
+
197
+ Records loaded as Hashes read their keys with `hash_access`, see
198
+ [Hash Records](hash-records.md).
199
+
200
+ ## Fields serialized by default
201
+
202
+ `config.hide_by_default` chooses what a response serializes when the client
203
+ names no fields. Each mode fits its own case:
204
+
205
+ - `false`, the default: every attribute. Fits small serializers and internal
206
+ APIs, where a response is the whole record.
207
+ - `true`: no attribute, unless it has `hide: false`. Every call names its
208
+ fields with `only:` or `with:`, which fits mailers, exports and APIs whose
209
+ clients always choose fields. The `data` and `meta` attributes of
210
+ `Response` then need `hide: false` to stay in the response.
211
+ - `:auto`: every attribute except those with a preload or a batch loader:
212
+ relations preloaded with `auto_preload`, and batch-loaded values. A response
213
+ runs no extra query until a client requests such a field. Fits APIs whose
214
+ responses have relations or costly fields.
215
+
216
+ A plain relation without a preload stays visible with `:auto`, and so do
217
+ `data`, `meta` and `paging`: `method: :itself` is never preloaded. See
218
+ [Hiding by default](selecting-fields.md#hiding-by-default).
219
+
220
+ ### Another mode for some serializers
221
+
222
+ `Base` is a convention, not a requirement: the mode belongs to each
223
+ serializer. A serializer can change it, inherit another base serializer, or
224
+ inherit `Serega` directly with its own config. For example, a dashboard that
225
+ always shows its relations:
226
+
227
+ ```ruby
228
+ module Serializers
229
+ # Relations of the dashboard are serialized by default
230
+ class Dashboard < Base
231
+ config.hide_by_default = false
232
+
233
+ attribute :name
234
+ attribute :posts, serializer: Post, many: true
235
+ end
236
+
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
240
+ end
241
+ end
242
+ ```
243
+
244
+ A serializer reads the mode when it defines an attribute, so a change affects
245
+ the attributes defined after it. Attributes inherited from the parent keep the
246
+ parent's mode. Related serializers follow their own config.
247
+
248
+ ## Why `many: false`
249
+
250
+ Serega serializes a scope or an Array as a list. A response serializer gets
251
+ the whole list as one object, thus:
252
+
253
+ - `config.many = false` in `Response` builds one response from the list, not
254
+ one per user. A `many:` option of a call overrides it;
255
+ - `many: false` on `meta` passes the list as one object, so `Meta` reads the
256
+ whole list, for example its paging;
257
+ - `many: true` on `data` serializes each user.
258
+
259
+ ## Selecting fields
260
+
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:
273
+
274
+ ```ruby
275
+ USERS_SERIALIZER.to_json(users, only: "data(id,name),meta")
276
+ # => {"data":[{"id":1,"name":"Felonious Gru"}],"meta":{"version":"1","paging":{...}}}
277
+
278
+ USERS_SERIALIZER.to_json(users, only: "data(id)")
279
+ # => {"data":[{"id":1}]}
280
+
281
+ USERS_SERIALIZER.to_json(users, only: "data(id),meta(paging(total_count))")
282
+ # => {"data":[{"id":1}],"meta":{"paging":{"total_count":1}}}
283
+ ```
284
+
285
+ To keep an existing `?fields=id,name` parameter that names the fields of the
286
+ records, nest its names under `data`:
287
+
288
+ ```ruby
289
+ fields = params[:fields]&.split(",") # ?fields=id,name
290
+ USERS_SERIALIZER.to_json(users, only: fields && {data: fields, meta: nil})
291
+ ```
292
+
293
+ 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`.
@@ -0,0 +1,164 @@
1
+ # Selecting Fields
2
+
3
+ All attributes are serialized by default, except attributes defined with
4
+ `hide: true`. Three options change that:
5
+
6
+ - `:only` — serializes only the listed attributes;
7
+ - `:except` — skips the listed attributes;
8
+ - `:with` — adds hidden attributes.
9
+
10
+ ```ruby
11
+ class UserSerializer < Serega
12
+ attribute :username
13
+ attribute :first_name
14
+ attribute :email, hide: true
15
+ attribute :friends, serializer: UserSerializer, hide: true
16
+ end
17
+
18
+ UserSerializer.to_h(gru)
19
+ # => {username: "gru", first_name: "Felonious"}
20
+
21
+ UserSerializer.to_h(gru, only: :username)
22
+ # => {username: "gru"}
23
+
24
+ UserSerializer.to_h(gru, except: :first_name)
25
+ # => {username: "gru"}
26
+
27
+ UserSerializer.to_h(gru, with: :email)
28
+ # => {username: "gru", first_name: "Felonious", email: "gru@example.com"}
29
+ ```
30
+
31
+ ## Table of Contents
32
+
33
+ <!-- toc -->
34
+
35
+ - [Nested fields](#nested-fields)
36
+ - [Combining options](#combining-options)
37
+ - [Fields from a request](#fields-from-a-request)
38
+ - [Unknown fields](#unknown-fields)
39
+ - [Hiding by default](#hiding-by-default)
40
+
41
+ <!-- tocstop -->
42
+
43
+ ## Nested fields
44
+
45
+ Select fields of relations with a Hash. Fields are Symbols, Strings, Arrays,
46
+ Hashes or their combinations.
47
+
48
+ ```ruby
49
+ UserSerializer.to_h(gru, only: [:username, {friends: :email}])
50
+ # => {username: "gru", friends: [{email: "lucy@example.com"}]}
51
+
52
+ UserSerializer.to_h(gru, with: {friends: :email})
53
+ # => {
54
+ # username: "gru", first_name: "Felonious",
55
+ # friends: [{username: "lucy", first_name: "Lucy", email: "lucy@example.com"}]
56
+ # }
57
+
58
+ UserSerializer.to_h(gru, with: :friends, except: {friends: :first_name})
59
+ # => {username: "gru", first_name: "Felonious", friends: [{username: "lucy"}]}
60
+ ```
61
+
62
+ A relation listed in `:only` without nested fields serializes its default
63
+ fields.
64
+
65
+ ## Combining options
66
+
67
+ The options combine at each level: the root serializer and every relation
68
+ read their own part of `:only`, `:except` and `:with`.
69
+
70
+ When options name the same field, `:except` wins. `:only` and `:with` both
71
+ show the fields they name, hidden fields too:
72
+
73
+ ```ruby
74
+ UserSerializer.to_h(gru, only: [:username, :email], except: :email)
75
+ # => {username: "gru"}
76
+
77
+ UserSerializer.to_h(gru, only: :username, with: :email)
78
+ # => {username: "gru", email: "gru@example.com"}
79
+ ```
80
+
81
+ `:only` hides the other fields of a level when it names a field of that level
82
+ without nested fields, or when `:except` and `:with` name no fields of that
83
+ level. Otherwise the level starts with its default fields, and a relation in
84
+ `:only` only selects the fields of that relation. Thus `:only` and `:with` on
85
+ one level equal one `:only` with the fields of both, when `:only` names a
86
+ field of that level without nested fields.
87
+
88
+ Each level can use its own option. The Result column lists the serialized
89
+ fields:
90
+
91
+ | Root | Friends | Fields | Result |
92
+ |---|---|---|---|
93
+ | only | except | `only: [:username, :friends], except: {friends: :first_name}` | username, friends(username) |
94
+ | only | with | `only: [:email, :friends], with: {friends: :email}` | email, friends(username, first_name, email) |
95
+ | except | only | `except: :first_name, only: {friends: :email}` | username, friends(email) |
96
+ | except | with | `except: :first_name, with: {friends: :email}` | username, friends(username, first_name, email) |
97
+ | with | only | `with: :email, only: {friends: :username}` | username, first_name, email, friends(username) |
98
+ | with | except | `with: :friends, except: {friends: :first_name}` | username, first_name, friends(username) |
99
+ | only | only | `only: {friends: :username}` | friends(username) |
100
+ | default | only | `with: :friends, only: {friends: :username}` | username, first_name, friends(username) |
101
+
102
+ ## Fields from a request
103
+
104
+ Fields can be one String, with nested fields in parentheses. This fits query
105
+ parameters like `GET /users?fields=username,friends(username,email)`.
106
+
107
+ ```ruby
108
+ UserSerializer.to_h(gru, only: "username,friends(username,email)")
109
+ # => {username: "gru", friends: [{username: "lucy", email: "lucy@example.com"}]}
110
+
111
+ UserSerializer.to_h(users, only: params[:fields]) # all default fields when params[:fields] is nil
112
+ ```
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
+
121
+ ## Unknown fields
122
+
123
+ An unknown field raises `Serega::AttributeNotExist`. Its `#serializer` and
124
+ `#attributes` methods return the serializer and the unknown fields.
125
+
126
+ ```ruby
127
+ UserSerializer.to_h(gru, only: [:nickname, {friends: :age}])
128
+ # => Serega::AttributeNotExist: Not existing attributes: nickname, friends(age)
129
+ ```
130
+
131
+ ## Hiding by default
132
+
133
+ `config.hide_by_default = true` hides every attribute that has no
134
+ `hide: false` option. `config.hide_by_default = :auto` hides attributes that
135
+ need [preloads](preloads.md) or [batch loaders](batch-loading.md), so clients
136
+ request expensive fields explicitly.
137
+
138
+ ```ruby
139
+ class UserSerializer < Serega
140
+ config.hide_by_default = true
141
+
142
+ attribute :username
143
+ attribute :first_name, hide: false
144
+ end
145
+
146
+ UserSerializer.to_h(gru) # => {first_name: "Felonious"}
147
+ ```
148
+
149
+ With `:auto` and the serializers of [Preloads](preloads.md), a request without
150
+ the expensive fields loads nothing:
151
+
152
+ ```ruby
153
+ class AppSerializer < Serega
154
+ plugin :activerecord_preloads
155
+ config.auto_preload = true
156
+ config.hide_by_default = :auto
157
+ end
158
+
159
+ UserSerializer.to_h(users)
160
+ # => [{name: "Felonious"}, ...], no preloads
161
+
162
+ UserSerializer.to_h(users, with: [:followers_count, {albums: :downloads_count}])
163
+ # preloads user_stats and albums for users, downloads for albums
164
+ ```
@@ -0,0 +1,113 @@
1
+ # Serializing
2
+
3
+ ```ruby
4
+ class UserSerializer < Serega
5
+ attribute :username
6
+ attribute :posts, serializer: PostSerializer
7
+ end
8
+
9
+ UserSerializer.to_h(user)
10
+ # => {username: "gru", posts: [{title: "Stealing the Moon"}]}
11
+
12
+ UserSerializer.to_h([user])
13
+ # => [{username: "gru", posts: [{title: "Stealing the Moon"}]}]
14
+
15
+ UserSerializer.to_h(nil) # => nil
16
+ UserSerializer.to_h([]) # => []
17
+ UserSerializer.to_json(nil) # => "null"
18
+ ```
19
+
20
+ `.call` is an alias of `.to_h`. Both accept the [field
21
+ selection](selecting-fields.md) options `:only`, `:except` and `:with`, and the
22
+ serialization options:
23
+
24
+ - `:context` — data for attribute values and conditions, see
25
+ [Context](context.md);
26
+ - `:many` — serializes the object as a list (`true`) or as one object
27
+ (`false`). By default, an `Enumerable` that is not a `Hash` or `Struct` is a
28
+ list. Serega remembers the answer for the class of the object. Pass it when
29
+ you know, to skip the check. `config.many` sets the default of a
30
+ serializer, for example `config.many = false` for a serializer that always
31
+ gets a list as one object.
32
+
33
+ The options are keyword arguments. Pass a Hash of options with `**`:
34
+
35
+ ```ruby
36
+ UserSerializer.to_h(user, **options)
37
+ ```
38
+
39
+ An unknown option raises `ArgumentError`. With `plugin :root` or
40
+ `plugin :context_metadata`, it raises `Serega::SeregaError`.
41
+
42
+ ## Table of Contents
43
+
44
+ <!-- toc -->
45
+
46
+ - [JSON](#json)
47
+ - [Struct and Data results](#struct-and-data-results)
48
+ - [Reusing a serializer](#reusing-a-serializer)
49
+ - [Plan cache](#plan-cache)
50
+
51
+ <!-- tocstop -->
52
+
53
+ ## JSON
54
+
55
+ `.to_json` returns a JSON String: `JSON.generate` of the `.to_h` result. It
56
+ takes the same options as `.to_h`.
57
+
58
+ ```ruby
59
+ UserSerializer.to_json(user)
60
+ # => "{\"username\":\"gru\",\"posts\":[{\"title\":\"Stealing the Moon\"}]}"
61
+
62
+ render json: UserSerializer.to_json(user) # Rails renders the String as it is
63
+ ```
64
+
65
+ To encode with another JSON library, pass it the `.to_h` result:
66
+
67
+ ```ruby
68
+ Oj.dump(UserSerializer.to_h(user), mode: :compat)
69
+ ```
70
+
71
+ ## Struct and Data results
72
+
73
+ `.to_struct` returns `Struct` objects and `.to_data` returns `Data` objects,
74
+ nested relations included. `.to_struct` is as fast as `.to_h`.
75
+
76
+ ```ruby
77
+ UserSerializer.to_struct(user)
78
+ # => #<struct username="gru", posts=[#<struct title="Stealing the Moon">]>
79
+
80
+ UserSerializer.to_data(user)
81
+ # => #<data username="gru", posts=[#<data title="Stealing the Moon">]>
82
+
83
+ UserSerializer.to_data(user).posts.first.title # => "Stealing the Moon"
84
+ ```
85
+
86
+ An attribute named `initialize` or a name that Ruby does not accept as a
87
+ member, for example `name=`, raises `Serega::SeregaError`. A member named like
88
+ a method of `Struct` or `Data`, for example `hash`, replaces this method in the
89
+ result.
90
+
91
+ ## Reusing a serializer
92
+
93
+ A serializer instance prepares its serialization plan once. Reuse it to
94
+ serialize many times with the same fields. Its methods take the
95
+ serialization options:
96
+
97
+ ```ruby
98
+ serializer = UserSerializer.new(only: [:username])
99
+ serializer.to_h(user, many: false)
100
+ serializer.to_json(users, context: {current_user: current_user})
101
+ ```
102
+
103
+ Class methods cache plans too, see [Plan cache](#plan-cache).
104
+
105
+ ## Plan cache
106
+
107
+ A serialization plan lists the fields to serialize. Serega caches plans by the
108
+ `:only`, `:except` and `:with` options as given, so `[:id, :name]` and
109
+ `"id,name"` are cached separately. The plan without these options is always
110
+ cached.
111
+
112
+ Class methods keep up to `config.max_cached_plans_per_serializer_count` plans
113
+ per serializer, 20 by default. See [Configuration](configuration.md).