serega 0.51.0 → 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 (46) 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 +5 -4
  30. data/lib/serega/plan/cache.rb +13 -29
  31. data/lib/serega/plan/depth_limit.rb +27 -8
  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/selection.rb +10 -0
  35. data/lib/serega/plan.rb +7 -3
  36. data/lib/serega/plugins/context_metadata/context_metadata.rb +1 -1
  37. data/lib/serega/plugins/root/root.rb +10 -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 +2 -2
  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 +54 -46
  45. data/sig/serega.rbs +10 -8
  46. metadata +30 -6
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6438f2b6fe41afa2e0abbe8797f0fc6a6310ef1054dbf8015bfc1dfd1f2c08e6
4
- data.tar.gz: 66cb93142c582a79976b34091dc8bf0a032274ec526c77d9384aacf8590f013a
3
+ metadata.gz: 0e0bf08e498468db05502a670ba2d980e8c1294b909e63c2a5e7b647b543fb83
4
+ data.tar.gz: 15fe428ba2c61ee524d701210048c9d26af1078ec5bbc476beb8f7b320d27d67
5
5
  SHA512:
6
- metadata.gz: bf3e63bd4060496f23a566464cb2b8b30485c5590aaf1cf2523d9afdd357725adbb0919a0301b2c45d1d4aadc9706c868e7e9001a9200d28b9b6bf97b159485f
7
- data.tar.gz: 87f6e1149f650de7f4571cc1a10d8b9f59a09af343c52945a242442402bc982ad5feaf1cd9af9b5c40915b1f6b9d1a916cd29e905cb613c9385bf6806f42528c
6
+ metadata.gz: 5d6ddc6a0b696369c0210bd324105fb02f6e9713c9e4d31c188492174371f35aaa9a62d06a2384d75cdafa4cbdbea8faa40dc9db58bccaafc363d9b6d8853351
7
+ data.tar.gz: dbac978f6f5a302cdf764436e2faa5b9ce88fd55282c910b881f9a030031e1bae4a21b9fd3075821d7753b57b849138facf3351a0aa1c48bc78154b2a0f3621a
data/README.md CHANGED
@@ -12,17 +12,16 @@
12
12
  **Serialize exactly what was asked. Load exactly what is needed.**
13
13
 
14
14
  [![Gem Version](https://badge.fury.io/rb/serega.svg)](https://badge.fury.io/rb/serega)
15
- [![GitHub Actions][build-badge]][build]
16
- ![Coverage 100%](https://img.shields.io/badge/coverage-100%25-brightgreen)
17
- ![Zero dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)
18
- ![Ruby >= 3.3](https://img.shields.io/badge/ruby-%3E%3D%203.3-red)
15
+ [![GitHub Actions](https://github.com/andreyruby/serega/actions/workflows/main.yml/badge.svg?event=push)][build]
16
+ [![Coverage 100%](https://img.shields.io/badge/coverage-100%25-brightgreen)][build]
17
+ [![Zero dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)][rubygems]
18
+ [![Ruby >= 3.3](https://img.shields.io/badge/ruby-%3E%3D%203.3-brightgreen)][gemspec]
19
19
 
20
20
  Serega is a Ruby serializer that turns your objects into Hashes ready for JSON.
21
21
  Clients choose the fields they need, and Serega loads only the data those
22
22
  fields use — in a few queries, with no N+1.
23
23
 
24
24
  - ⚡ **Fast** — serialization code is generated per field selection and cached.
25
- [See benchmarks](#benchmarks).
26
25
  - 🎯 **Clients choose fields** — `?fields=name,posts(title)` works out of the
27
26
  box, nested at any depth.
28
27
  - 🧺 **No N+1** — associations are preloaded and batch loaders run once per
@@ -30,6 +29,10 @@ fields use — in a few queries, with no N+1.
30
29
  - 🪶 **No dependencies** — plain Ruby, works with Rails, Hanami, Roda, Sinatra
31
30
  or no framework at all.
32
31
 
32
+ [Quick start][start] · [Benchmarks][bench] · [Selecting fields][fields] · [Preloads][preloads] · [Batch loading][batch]
33
+
34
+ [Attribute options][options]: `method` · `delegate` · `const` · `default` · `format` · `hash_access` · `batch` · …
35
+
33
36
  ## Show me
34
37
 
35
38
  ```ruby
@@ -52,10 +55,10 @@ class PostSerializer < AppSerializer
52
55
  end
53
56
 
54
57
  UserSerializer.to_h(User.all)
55
- # => [{name: "Bruce Wayne"}, ...] 1 query
58
+ # => [{name: "Felonious Gru"}, ...] 1 query
56
59
 
57
60
  UserSerializer.to_h(User.all, only: "name,posts(title,comments_count)")
58
- # => [{name: "Bruce Wayne", posts: [{title: "Gotham at night", comments_count: 12}, ...]}, ...]
61
+ # => [{name: "Felonious Gru", posts: [{title: "Stealing the Moon", comments_count: 12}, ...]}, ...]
59
62
  # 3 queries, for any number of users
60
63
  ```
61
64
 
@@ -67,7 +70,7 @@ bundle add serega
67
70
 
68
71
  ## Quick start
69
72
 
70
- Define a base serializer with the setup your app uses. Every serializer
73
+ A base serializer can hold the setup your app uses. Every serializer
71
74
  inherits it.
72
75
 
73
76
  ```ruby
@@ -99,12 +102,6 @@ class UsersController < ApplicationController
99
102
  end
100
103
  ```
101
104
 
102
- ## Benchmarks
103
-
104
- Serega is on par with the fastest Ruby serializers in speed and allocations,
105
- and in some cases beats them. Results, the details of each case and how to run
106
- them: [benchmarks/README.md](https://github.com/andreyruby/serega/blob/master/benchmarks/README.md).
107
-
108
105
  ## Features
109
106
 
110
107
  ### Select fields
@@ -160,9 +157,9 @@ class EventSerializer < Serega
160
157
  attribute :title, hash_access: true # reads event[:title]
161
158
  end
162
159
 
163
- UserSerializer.to_h(user) # => {name: "Bruce Wayne"}
164
- UserSerializer.to_struct(user) # => #<struct name="Bruce Wayne">
165
- UserSerializer.to_data(user) # => #<data name="Bruce Wayne">
160
+ UserSerializer.to_h(user) # => {name: "Felonious Gru"}
161
+ UserSerializer.to_struct(user) # => #<struct name="Felonious Gru">
162
+ UserSerializer.to_data(user) # => #<data name="Felonious Gru">
166
163
  ```
167
164
 
168
165
  → [Hash records guide](docs/hash-records.md) ·
@@ -185,17 +182,40 @@ Ractor.new(user) { |user| UserSerializer.to_h(user) }.value
185
182
 
186
183
  ### And more
187
184
 
188
- - [Attributes](docs/attributes.md) — all attribute options, relations and nested serializers
185
+ - [Attributes](docs/attributes.md) — all attribute options
186
+ - [Relations](docs/relations.md) — nested serializers, `many:`, depth limit
187
+ - [Presets](docs/presets.md) — named field selections, also on relations
188
+ - [camelCase keys](docs/camel-case.md) — `firstName` keys from `first_name` attributes
189
189
  - [Conditional attributes](docs/conditional-attributes.md) — `if:`, `unless:`, `if_value:`, `unless_value:`
190
190
  - [Context](docs/context.md) — pass `current_user` and other request data
191
191
  - [Presenter](docs/presenter.md) — write computed attributes as methods
192
192
  - [Prepare initial objects](docs/prepare-initial-objects.md) — serialize records by ids
193
193
  - [Configuration](docs/configuration.md) — all config options
194
- - [Root key and metadata](docs/root-and-metadata.md) — wrap results in `{data: ...}` and add metadata
194
+ - [Response serializers](docs/responses.md) — wrap results in `{data: ..., meta: ...}`
195
+
196
+ ## Benchmarks
197
+
198
+ Serega is on par with the fastest Ruby serializers in speed and allocations,
199
+ and in some cases beats them. Serializations per second of 100 posts with their
200
+ author and 10 comments each, more is better:
201
+
202
+ <!-- benchmarks:summary -->
203
+ | Serializer | 100 posts with relations, JSON per second |
204
+ |--------------------------|------------------------------------------:|
205
+ | **Serega** | 1,317 |
206
+ | panko_serializer | 1,099 |
207
+ | oj_serializers | 987 |
208
+ | alba | 412 |
209
+ | blueprinter | 308 |
210
+ | active_model_serializers | 45 |
211
+ <!-- benchmarks:summary:end -->
212
+
213
+ Results of all cases, the details of each case and how to run them:
214
+ [benchmarks/README.md](https://github.com/andreyruby/serega/blob/master/benchmarks/README.md).
195
215
 
196
216
  ## Documentation
197
217
 
198
- - 📋 [Cheatsheet](CHEATSHEET.md) — every option on one page
218
+ - 📋 [Cheatsheet](https://github.com/andreyruby/serega/blob/master/CHEATSHEET.md) — every option on one page
199
219
  - 📚 [Guides](docs/README.md) — each feature in depth
200
220
  - 🔎 [Documentation site](https://andreyruby.github.io/serega/) — guides and API reference
201
221
  - 🔤 [Type signatures](https://github.com/andreyruby/serega/tree/master/sig) — RBS of the public API
@@ -220,5 +240,12 @@ Bug reports, pull requests and ideas are welcome!
220
240
  The gem is available as open source under the terms of the
221
241
  [MIT License](https://opensource.org/licenses/MIT).
222
242
 
223
- [build-badge]: https://github.com/andreyruby/serega/actions/workflows/main.yml/badge.svg?event=push
224
243
  [build]: https://github.com/andreyruby/serega/actions/workflows/main.yml
244
+ [start]: #quick-start
245
+ [bench]: #benchmarks
246
+ [fields]: docs/selecting-fields.md#fields-from-a-request
247
+ [preloads]: docs/preloads.md
248
+ [batch]: docs/batch-loading.md
249
+ [options]: docs/attributes.md#all-options
250
+ [rubygems]: https://rubygems.org/gems/serega
251
+ [gemspec]: https://github.com/andreyruby/serega/blob/master/serega.gemspec
data/VERSION CHANGED
@@ -1 +1 @@
1
- 0.51.0
1
+ 0.52.0
data/docs/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # Serega Guides
2
+
3
+ Each guide covers one feature in depth. For a one-page overview of every option,
4
+ see the [Cheatsheet](https://github.com/andreyruby/serega/blob/master/CHEATSHEET.md).
5
+
6
+ ## Basics
7
+
8
+ - [Attributes](attributes.md) — define serializers and attributes
9
+ - [Relations](relations.md) — nested serializers, `:many`, depth limit
10
+ - [Serializing](serializing.md) — `to_h`, `to_struct`, `to_data`
11
+ - [Response Serializers](responses.md) — wrap results in `{data: ..., meta: ...}`
12
+ with a serializer
13
+ - [Root Key and Metadata](root-and-metadata.md) — deprecated plugins, see
14
+ Response Serializers
15
+ - [Migrating from the Root and Metadata Plugins](migrating-from-root-and-metadata.md)
16
+ — replace the deprecated plugins with a response serializer
17
+ - [Selecting Fields](selecting-fields.md) — `:only`, `:except`, `:with`
18
+ - [Presets](presets.md) — named field selections, also on relations
19
+ - [Context](context.md) — pass `current_user` and other request data
20
+ - [Conditional Attributes](conditional-attributes.md) — `:if`, `:unless`,
21
+ `:if_value`, `:unless_value`
22
+ - [Formatters](formatters.md) — format dates, money and other values
23
+ - [camelCase Keys](camel-case.md) — `firstName` keys from `first_name` attributes
24
+
25
+ ## Loading data without N+1
26
+
27
+ - [Preloads](preloads.md) — preload associations used by requested fields
28
+ - [Batch Loading](batch-loading.md) — load data for all serialized objects at once
29
+ - [Testing Serializers](testing.md) — test attributes, value classes and batch loaders
30
+
31
+ ## Data sources
32
+
33
+ - [Hash Records](hash-records.md) — read attribute values from Hash keys
34
+ - [Prepare Initial Objects](prepare-initial-objects.md) — serialize records by ids
35
+ - [Presenter](presenter.md) — write computed attributes as methods
36
+
37
+ ## Advanced
38
+
39
+ - [Configuration](configuration.md) — all config options
40
+ - [Ractors](ractors.md) — serialize in parallel Ractors
41
+ - [Errors](errors.md) — errors Serega raises
@@ -0,0 +1,248 @@
1
+ # Attributes
2
+
3
+ A serializer is a class that lists attributes. Each attribute adds a key to the
4
+ result, and its options say where the value comes from.
5
+
6
+ ```ruby
7
+ class UserSerializer < Serega
8
+ attribute :first_name
9
+ attribute :last_name
10
+ end
11
+
12
+ UserSerializer.to_h(user) # => {first_name: "Felonious", last_name: "Gru"}
13
+ ```
14
+
15
+ ## Table of Contents
16
+
17
+ <!-- toc -->
18
+
19
+ - [All options](#all-options)
20
+ - [Shared config in a base serializer](#shared-config-in-a-base-serializer)
21
+ - [Configure before the first serialization](#configure-before-the-first-serialization)
22
+ - [Attribute values](#attribute-values)
23
+ - [`:method`](#method)
24
+ - [`:value`](#value)
25
+ - [`:delegate`](#delegate)
26
+ - [`:const`](#const)
27
+ - [`:default`](#default)
28
+ - [Other sources](#other-sources)
29
+ - [Hidden attributes](#hidden-attributes)
30
+ - [Relations](#relations)
31
+ - [Conditions and formatting](#conditions-and-formatting)
32
+ - [Attribute names](#attribute-names)
33
+ - [Listing attributes](#listing-attributes)
34
+
35
+ <!-- tocstop -->
36
+
37
+ ## All options
38
+
39
+ | Option | Purpose |
40
+ |---|---|
41
+ | `method` | [Read another method](#method) |
42
+ | `value` | [Compute the value](#value) |
43
+ | `delegate` | [Read from an associated object](#delegate) |
44
+ | `const` | [Serialize a constant](#const) |
45
+ | `default` | [Replace `nil`](#default) |
46
+ | `batch` | [Load values for all objects at once](batch-loading.md) |
47
+ | `hash_access` | [Read Hash keys](hash-records.md) |
48
+ | `hide` | [Exclude unless requested](#hidden-attributes) |
49
+ | `serializer` | [Serialize with another serializer](relations.md#serializer) |
50
+ | `many` | [Mark a list](relations.md#many) |
51
+ | `preset` | [Serialize the fields of a preset of the relation](relations.md#preset) |
52
+ | `only`, `with`, `except` | [Select the fields of the relation](relations.md#only-with-except) |
53
+ | `preload` | [Preload associations](relations.md#preload) |
54
+ | `base_serializer` | [Base of a block-defined serializer](relations.md#nested-serializers-defined-with-a-block) |
55
+ | `if`, `unless`, `if_value`, `unless_value` | [Conditional attributes](conditional-attributes.md) |
56
+ | `format` | [Format the value](formatters.md) |
57
+
58
+ ## Shared config in a base serializer
59
+
60
+ A base serializer can hold the plugins and config your app uses. Every
61
+ serializer inherits plugins, config and attributes from its superclass.
62
+
63
+ ```ruby
64
+ class AppSerializer < Serega
65
+ plugin :activerecord_preloads
66
+ config.auto_preload = true
67
+ config.base_serializer = self # nested serializers defined with a block inherit AppSerializer
68
+ end
69
+
70
+ class UserSerializer < AppSerializer
71
+ attribute :first_name
72
+ end
73
+
74
+ class CommentSerializer < AppSerializer
75
+ attribute :text
76
+ end
77
+ ```
78
+
79
+ ## Configure before the first serialization
80
+
81
+ Configure a serializer fully before it serializes anything. A serializer is
82
+ locked after its first serialization, directly or as a nested serializer.
83
+
84
+ ```ruby
85
+ UserSerializer.to_h(user)
86
+
87
+ UserSerializer.attribute :nickname
88
+ # => Serega::SeregaError: UserSerializer can not be changed after it was used for serialization
89
+
90
+ UserSerializer.config.auto_preload = false
91
+ # => FrozenError
92
+
93
+ class AdminSerializer < UserSerializer
94
+ attribute :nickname # subclasses of a locked serializer can be changed
95
+ end
96
+ ```
97
+
98
+ A locked serializer raises `Serega::SeregaError` on new attributes, plugins,
99
+ batch loaders, presenter methods, meta attributes, `preload_with` and
100
+ `prepare_initial_objects` handlers, and `FrozenError` on config changes.
101
+
102
+ ## Attribute values
103
+
104
+ By default, the value is the result of the method with the attribute name:
105
+ `attribute :first_name` reads `user.first_name`. The options below change that.
106
+
107
+ ### `:method`
108
+
109
+ Reads the value from another method.
110
+
111
+ ```ruby
112
+ attribute :name, method: :first_name # user.first_name
113
+ # => {name: "Felonious"}
114
+ ```
115
+
116
+ With [`:hash_access`](hash-records.md), `:method` names a Hash key.
117
+
118
+ ### `:value`
119
+
120
+ Computes the value with a Proc or any object that responds to `#call`.
121
+
122
+ ```ruby
123
+ attribute :full_name, value: proc { |user| "#{user.first_name} #{user.last_name}" }
124
+ attribute :current, value: proc { |user, ctx| user == ctx[:current_user] }
125
+ attribute :current, value: proc { |user, ctx:| user == ctx[:current_user] }
126
+ attribute :api_version, value: proc { 2 }
127
+ attribute :full_name, value: FullName # FullName.call(user)
128
+ attribute :link, value: UserLink.new # UserLink.new.call(user)
129
+ ```
130
+
131
+ The callable receives the object to serialize and, optionally, the
132
+ [context](context.md) as a second parameter or the `:ctx` keyword. The
133
+ `:batches` keyword gives the results of the attribute's [batch loaders](batch-loading.md).
134
+
135
+ An existing callable class or instance needs no `proc` wrapper:
136
+ `value: UserLink.new` replaces `value: proc { |user| UserLink.new.call(user) }`.
137
+ The instance is built once, when the serializer is defined, and every
138
+ serialization shares it, so it keeps no per-call state.
139
+
140
+ ### `:delegate`
141
+
142
+ Reads the value from an associated object.
143
+
144
+ ```ruby
145
+ attribute :city, delegate: {to: :profile} # user.profile.city
146
+ attribute :profile_name, delegate: {to: :profile, method: :first_name} # user.profile.first_name
147
+ attribute :city, delegate: {to: :profile, allow_nil: true} # nil when user.profile is nil
148
+ ```
149
+
150
+ Without `allow_nil: true`, a `nil` associated object raises `NoMethodError`.
151
+ `config.delegate_default_allow_nil = true` makes `allow_nil: true` the default.
152
+ Delegates also read Hash records, see [Hash records](hash-records.md).
153
+
154
+ ### `:const`
155
+
156
+ Serializes a constant value.
157
+
158
+ ```ruby
159
+ attribute :type, const: "user"
160
+ # => {type: "user"}
161
+ ```
162
+
163
+ ### `:default`
164
+
165
+ Replaces a `nil` value.
166
+
167
+ ```ruby
168
+ attribute :nickname, default: ""
169
+ attribute :active, default: false
170
+ attribute :city, delegate: {to: :profile, allow_nil: true}, default: "Unknown"
171
+ ```
172
+
173
+ ### Other sources
174
+
175
+ - [`:batch`](batch-loading.md) loads values for all serialized objects at once.
176
+ - [`:hash_access`](hash-records.md) reads values from Hash keys.
177
+
178
+ `:method`, `:value` and `:const` can not be combined, and `:batch` can not be
179
+ combined with `:method` or `:const`.
180
+
181
+ ## Hidden attributes
182
+
183
+ `hide: true` excludes an attribute unless it is requested with `:with` or
184
+ `:only`. See [Selecting fields](selecting-fields.md).
185
+
186
+ ```ruby
187
+ class UserSerializer < Serega
188
+ attribute :first_name
189
+ attribute :last_name, hide: true
190
+ end
191
+
192
+ UserSerializer.to_h(user) # => {first_name: "Felonious"}
193
+ UserSerializer.to_h(user, with: :last_name) # => {first_name: "Felonious", last_name: "Gru"}
194
+ ```
195
+
196
+ ## Relations
197
+
198
+ An attribute with `:serializer`, or with a block, serializes its value with
199
+ another serializer. See [Relations](relations.md).
200
+
201
+ ```ruby
202
+ attribute :posts, serializer: PostSerializer, many: true
203
+ ```
204
+
205
+ ## Conditions and formatting
206
+
207
+ ```ruby
208
+ attribute :email, if: proc { |user, ctx| user == ctx[:current_user] }
209
+ attribute :email, if_value: :present?
210
+ attribute :created_at, format: :iso8601
211
+ ```
212
+
213
+ See [Conditional attributes](conditional-attributes.md) for `:if`, `:unless`,
214
+ `:if_value` and `:unless_value`, and [Formatters](formatters.md) for `:format`.
215
+
216
+ ## Attribute names
217
+
218
+ Attribute names may contain only `a-z`, `A-Z`, `0-9`, `_`, `-` and `~`, so
219
+ they can be used in URLs without escaping. Other names raise
220
+ `Serega::SeregaError`. `config.check_attribute_name = false` turns the check
221
+ off.
222
+
223
+ The name is the serialized key as is. A camelCase key reads its value with
224
+ `:method`:
225
+
226
+ ```ruby
227
+ attribute :firstName, method: :first_name
228
+ # => {firstName: "Felonious"}
229
+ ```
230
+
231
+ For camelCase keys in every serializer, see [camelCase Keys](camel-case.md).
232
+
233
+ ## Listing attributes
234
+
235
+ `.attributes` returns the attributes by name, hidden and inherited ones too:
236
+
237
+ ```ruby
238
+ class UserSerializer < Serega
239
+ attribute :username
240
+ attribute :email, hide: true
241
+ end
242
+
243
+ class AdminSerializer < UserSerializer
244
+ attribute :role
245
+ end
246
+
247
+ AdminSerializer.attributes.keys # => [:username, :email, :role]
248
+ ```
@@ -0,0 +1,207 @@
1
+ # Batch Loading
2
+
3
+ A batch loader loads data for all serialized objects at once, so serializing
4
+ 100 users runs one query, not 100.
5
+
6
+ ```ruby
7
+ class UserSerializer < Serega
8
+ batch :followers_count, ->(users) { Follow.where(user: users).group(:user_id).count }
9
+
10
+ attribute :name
11
+ attribute :followers_count, batch: true
12
+ end
13
+
14
+ UserSerializer.to_h(users)
15
+ # SELECT COUNT(*), user_id FROM follows WHERE user_id IN (1, 2, ...) GROUP BY user_id
16
+ # => [{name: "Felonious", followers_count: 7}, {name: "Lucy", followers_count: 3}]
17
+ ```
18
+
19
+ A loader receives the objects and returns a Hash of values by object id. The
20
+ attribute value is `batches[:followers_count][user.id]`, `nil` for a missing
21
+ id.
22
+
23
+ A loader runs once per serialization for all objects of a relation: for
24
+ `users(posts(comments_count))`, the `comments_count` loader runs once for the
25
+ posts of all users. A loader of an attribute that is not serialized does not
26
+ run.
27
+
28
+ ## Table of Contents
29
+
30
+ <!-- toc -->
31
+
32
+ - [Defining loaders](#defining-loaders)
33
+ - [Using loaders](#using-loaders)
34
+ - [Values for the current user](#values-for-the-current-user)
35
+ - [Defaults and combined loaders](#defaults-and-combined-loaders)
36
+ - [Records without an `id`](#records-without-an-id)
37
+ - [Loading relations in batches](#loading-relations-in-batches)
38
+
39
+ <!-- tocstop -->
40
+
41
+ ## Defining loaders
42
+
43
+ `batch` defines a named loader. Child serializers inherit it, and a child
44
+ that defines a loader with the same name uses its own, while the parent keeps
45
+ the original.
46
+
47
+ ```ruby
48
+ class UserSerializer < Serega
49
+ batch :likes_count, ->(users) { Like.where(user: users).group(:user_id).count }
50
+ batch :views_count, ViewsCountLoader # responds to #call
51
+ batch(:badges) { |users| Badge.for_users(users) } # block
52
+ batch :rank, ->(users, ctx) { Rank.for(users, ctx[:season]) } # with context
53
+ batch :rank, ->(users, ctx:) { Rank.for(users, ctx[:season]) } # :ctx keyword
54
+ end
55
+ ```
56
+
57
+ A loader with logic of its own fits a class in its own file, such as
58
+ `app/serializers/loaders/views_count_loader.rb`: any object that responds to
59
+ `#call` works, and it can be tested without a serializer.
60
+
61
+ ## Using loaders
62
+
63
+ ```ruby
64
+ class UserSerializer < Serega
65
+ # The loader named after the attribute. It must be defined before the attribute.
66
+ attribute :likes_count, batch: true
67
+
68
+ # A loader with another name
69
+ attribute :likes, batch: :likes_count
70
+
71
+ # A loader that belongs to this attribute
72
+ attribute :followers_count, batch: ->(users) { Follow.where(user: users).group(:user_id).count }
73
+ end
74
+ ```
75
+
76
+ `batch: true` and `batch: :name` raise `Serega::SeregaError` when no loader
77
+ with that name is defined.
78
+
79
+ Several attributes can use one loader. It runs once per serialization for all
80
+ of them:
81
+
82
+ ```ruby
83
+ class UserSerializer < Serega
84
+ batch :stats, ->(users) { UserStats.where(user: users).index_by(&:user_id) }
85
+
86
+ attribute :likes_count, batch: :stats, value: proc { |user, batches:| batches[:stats][user.id].likes }
87
+ attribute :views_count, batch: :stats, value: proc { |user, batches:| batches[:stats][user.id].views }
88
+ end
89
+ ```
90
+
91
+ ## Values for the current user
92
+
93
+ Values that depend on the current user, such as favorites or likes, read the
94
+ user from the [context](context.md). The loader returns only the ids with a
95
+ value, and `default:` fills in the others. For a guest, it returns an empty
96
+ Hash without a query.
97
+
98
+ ```ruby
99
+ class FavoriteCoursesLoader
100
+ def self.call(courses, ctx)
101
+ user = ctx[:current_user]
102
+ return {} unless user # a guest: no query
103
+
104
+ course_ids = Favorite.where(user: user, course: courses).pluck(:course_id)
105
+ course_ids.to_h { |id| [id, true] }
106
+ end
107
+ end
108
+
109
+ class CourseSerializer < Serega
110
+ attribute :title
111
+ attribute :favorite, batch: FavoriteCoursesLoader, default: false
112
+ end
113
+
114
+ CourseSerializer.to_h(courses, context: {current_user: user})
115
+ # SELECT "favorites"."course_id" FROM "favorites" WHERE "favorites"."user_id" = 1 AND "favorites"."course_id" IN (1, 2)
116
+ # => [{title: "Anatomy", favorite: true}, {title: "Figure Drawing", favorite: false}]
117
+
118
+ CourseSerializer.to_h(courses, context: {current_user: nil})
119
+ # => [{title: "Anatomy", favorite: false}, {title: "Figure Drawing", favorite: false}]
120
+ ```
121
+
122
+ ## Defaults and combined loaders
123
+
124
+ `:value` builds the value from the loaded batches, for example to set a default
125
+ or combine several loaders. A loader given directly to the attribute is found
126
+ under the attribute name.
127
+
128
+ ```ruby
129
+ attribute :followers_count, batch: true,
130
+ value: proc { |user, batches:| batches[:followers_count].fetch(user.id, 0) }
131
+
132
+ attribute :likes_count, batch: {use: [:facebook_likes, :x_likes]},
133
+ value: proc { |user, batches:| batches[:facebook_likes][user.id] + batches[:x_likes][user.id] }
134
+ ```
135
+
136
+ Several loaders in `:use` require `:value`. For a simple fallback,
137
+ [`default:`](attributes.md#default) also works: `batch: true, default: 0`.
138
+
139
+ ## Records without an `id`
140
+
141
+ Values are looked up by `object.id`. The `:id` option or
142
+ `config.batch_id_option` choose another method:
143
+
144
+ ```ruby
145
+ attribute :likes_count, batch: {use: :likes_count, id: :uuid}
146
+
147
+ class AppSerializer < Serega
148
+ config.batch_id_option = :uuid
149
+ end
150
+ ```
151
+
152
+ A foreign key works the same way. The loader returns the related records by
153
+ their ids, and `id:` names the key to look them up with. Records without the
154
+ key get `nil`, and the loader skips the request when no record has one:
155
+
156
+ ```ruby
157
+ class LessonSerializer < Serega
158
+ # Streams come from a video service, not the database
159
+ batch :streams, lambda { |lessons|
160
+ stream_ids = lessons.filter_map(&:stream_id)
161
+ stream_ids.empty? ? {} : VideoService.streams(stream_ids).to_h { |stream| [stream.id, stream] }
162
+ }
163
+
164
+ attribute :title
165
+ attribute :stream, serializer: StreamSerializer, batch: {use: :streams, id: :stream_id}
166
+ end
167
+ ```
168
+
169
+ For an ActiveRecord `belongs_to`, a [preload](preloads.md) does the same: it
170
+ runs no query when every foreign key is `nil`.
171
+
172
+ ## Loading relations in batches
173
+
174
+ A loader can return records for a relation serializer:
175
+
176
+ ```ruby
177
+ class UserSerializer < Serega
178
+ batch :posts, ->(users) { Post.where(user: users).group_by(&:user_id) }
179
+
180
+ attribute :posts, batch: true, serializer: PostSerializer
181
+ end
182
+ ```
183
+
184
+ The [preloads](preloads.md) of `PostSerializer` run for the loaded posts, so a
185
+ level can load with a batch and the next with preloads. For ActiveRecord
186
+ associations, preloads alone are usually simpler.
187
+
188
+ A related serializer can also summarize the loaded records instead of listing
189
+ them. With `config.many = false`, it receives each user's Array as one object:
190
+
191
+ ```ruby
192
+ class OrdersSummarySerializer < Serega
193
+ config.many = false # the user's orders as one object, not one item per order
194
+
195
+ attribute :count, method: :size
196
+ attribute :total_cents, value: proc { |orders| orders.sum(&:total_cents) }
197
+ end
198
+
199
+ class UserSerializer < Serega
200
+ batch :orders, ->(users) { Order.where(user: users).group_by(&:user_id) }
201
+
202
+ attribute :orders_summary, batch: :orders, serializer: OrdersSummarySerializer
203
+ end
204
+
205
+ UserSerializer.to_h(user)
206
+ # => {orders_summary: {count: 2, total_cents: 4998}}
207
+ ```