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.
- checksums.yaml +4 -4
- data/README.md +48 -21
- data/VERSION +1 -1
- data/docs/README.md +41 -0
- data/docs/attributes.md +248 -0
- data/docs/batch-loading.md +207 -0
- data/docs/camel-case.md +86 -0
- data/docs/conditional-attributes.md +165 -0
- data/docs/configuration.md +47 -0
- data/docs/context.md +34 -0
- data/docs/errors.md +38 -0
- data/docs/formatters.md +231 -0
- data/docs/hash-records.md +93 -0
- data/docs/migrating-from-root-and-metadata.md +50 -0
- data/docs/preloads.md +125 -0
- data/docs/prepare-initial-objects.md +72 -0
- data/docs/presenter.md +87 -0
- data/docs/presets.md +174 -0
- data/docs/ractors.md +54 -0
- data/docs/relations.md +233 -0
- data/docs/responses.md +548 -0
- data/docs/root-and-metadata.md +110 -0
- data/docs/selecting-fields.md +157 -0
- data/docs/serializing.md +113 -0
- data/docs/testing.md +230 -0
- data/lib/serega/attribute_normalizer.rb +26 -8
- data/lib/serega/attribute_normalizers/block.rb +3 -3
- data/lib/serega/config.rb +28 -13
- data/lib/serega/errors.rb +2 -2
- data/lib/serega/plan/cache.rb +13 -29
- data/lib/serega/plan/per_ractor_cache.rb +2 -2
- data/lib/serega/plan/point.rb +13 -2
- data/lib/serega/plan.rb +1 -1
- data/lib/serega/plugins/context_metadata/context_metadata.rb +1 -1
- data/lib/serega/plugins/root/root.rb +10 -10
- data/lib/serega/plugins.rb +13 -0
- data/lib/serega/result_code/relation_point_code.rb +3 -2
- data/lib/serega/source_group.rb +1 -1
- data/lib/serega/validations/attribute/check_block.rb +4 -7
- data/lib/serega/validations/attribute/check_opt_hash_access.rb +2 -3
- data/lib/serega/validations/check_batch_loader_params.rb +2 -1
- data/lib/serega.rb +30 -26
- data/sig/serega.rbs +10 -8
- metadata +23 -1
|
@@ -0,0 +1,157 @@
|
|
|
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
|
+
## Unknown fields
|
|
115
|
+
|
|
116
|
+
An unknown field raises `Serega::AttributeNotExist`. Its `#serializer` and
|
|
117
|
+
`#attributes` methods return the serializer and the unknown fields.
|
|
118
|
+
|
|
119
|
+
```ruby
|
|
120
|
+
UserSerializer.to_h(gru, only: [:nickname, {friends: :age}])
|
|
121
|
+
# => Serega::AttributeNotExist: Not existing attributes: nickname, friends(age)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Hiding by default
|
|
125
|
+
|
|
126
|
+
`config.hide_by_default = true` hides every attribute that has no
|
|
127
|
+
`hide: false` option. `config.hide_by_default = :auto` hides attributes that
|
|
128
|
+
need [preloads](preloads.md) or [batch loaders](batch-loading.md), so clients
|
|
129
|
+
request expensive fields explicitly.
|
|
130
|
+
|
|
131
|
+
```ruby
|
|
132
|
+
class UserSerializer < Serega
|
|
133
|
+
config.hide_by_default = true
|
|
134
|
+
|
|
135
|
+
attribute :username
|
|
136
|
+
attribute :first_name, hide: false
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
UserSerializer.to_h(gru) # => {first_name: "Felonious"}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
With `:auto` and the serializers of [Preloads](preloads.md), a request without
|
|
143
|
+
the expensive fields loads nothing:
|
|
144
|
+
|
|
145
|
+
```ruby
|
|
146
|
+
class AppSerializer < Serega
|
|
147
|
+
plugin :activerecord_preloads
|
|
148
|
+
config.auto_preload = true
|
|
149
|
+
config.hide_by_default = :auto
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
UserSerializer.to_h(users)
|
|
153
|
+
# => [{name: "Felonious"}, ...], no preloads
|
|
154
|
+
|
|
155
|
+
UserSerializer.to_h(users, with: [:followers_count, {albums: :downloads_count}])
|
|
156
|
+
# preloads user_stats and albums for users, downloads for albums
|
|
157
|
+
```
|
data/docs/serializing.md
ADDED
|
@@ -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).
|
data/docs/testing.md
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# Testing Serializers
|
|
2
|
+
|
|
3
|
+
Serega has no testing DSL and no test helpers. A serializer is a Ruby class,
|
|
4
|
+
and its specs call `to_h` like the app does and compare the result.
|
|
5
|
+
|
|
6
|
+
This guide is an example for inspiration: the way the gem author tests
|
|
7
|
+
serializers, not a rule. Keep what fits your app. The examples use RSpec and
|
|
8
|
+
FactoryBot, and the ideas work with any test tools.
|
|
9
|
+
|
|
10
|
+
The examples test this serializer:
|
|
11
|
+
|
|
12
|
+
```ruby
|
|
13
|
+
class UserSerializer < Serega
|
|
14
|
+
config.hide_by_default = :auto
|
|
15
|
+
|
|
16
|
+
attribute :first_name
|
|
17
|
+
attribute :email, if: proc { |user, ctx| user == ctx[:current_user] }
|
|
18
|
+
attribute :link, value: UserLink
|
|
19
|
+
attribute :followers_count, batch: FollowersCount, default: 0
|
|
20
|
+
end
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Table of Contents
|
|
24
|
+
|
|
25
|
+
<!-- toc -->
|
|
26
|
+
|
|
27
|
+
- [Testing one attribute at a time](#testing-one-attribute-at-a-time)
|
|
28
|
+
- [Testing the fields serialized by default](#testing-the-fields-serialized-by-default)
|
|
29
|
+
- [Testing attributes that read the context](#testing-attributes-that-read-the-context)
|
|
30
|
+
- [Moving complex values to their own classes](#moving-complex-values-to-their-own-classes)
|
|
31
|
+
- [Testing batch loaders](#testing-batch-loaders)
|
|
32
|
+
- [Counting queries with ActiveRecord](#counting-queries-with-activerecord)
|
|
33
|
+
|
|
34
|
+
<!-- tocstop -->
|
|
35
|
+
|
|
36
|
+
## Testing one attribute at a time
|
|
37
|
+
|
|
38
|
+
`selection` holds the [field selection](selecting-fields.md) options.
|
|
39
|
+
`{only: :first_name}` serializes one attribute, so each example builds only the
|
|
40
|
+
data that attribute needs:
|
|
41
|
+
|
|
42
|
+
```ruby
|
|
43
|
+
RSpec.describe UserSerializer do
|
|
44
|
+
subject(:result) { described_class.to_h(user, **selection, context: context) }
|
|
45
|
+
|
|
46
|
+
let(:user) { build_stubbed(:user, first_name: "Felonious", username: "gru", email: "gru@example.com") }
|
|
47
|
+
let(:context) { {} }
|
|
48
|
+
|
|
49
|
+
context "#first_name" do
|
|
50
|
+
let(:selection) { {only: :first_name} }
|
|
51
|
+
|
|
52
|
+
it "serializes the first name" do
|
|
53
|
+
expect(result).to eq(first_name: "Felonious")
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The user comes from `build_stubbed` and is never saved: a serializer only reads
|
|
60
|
+
the objects it gets, and such specs run fast. `build`, `User.new` or a `Struct`
|
|
61
|
+
works the same way.
|
|
62
|
+
|
|
63
|
+
## Testing the fields serialized by default
|
|
64
|
+
|
|
65
|
+
An empty `selection` serializes the fields a response has by default. With
|
|
66
|
+
`hide_by_default = :auto`, it catches a batch or a relation that starts to load
|
|
67
|
+
for every response:
|
|
68
|
+
|
|
69
|
+
```ruby
|
|
70
|
+
describe "default fields" do
|
|
71
|
+
let(:selection) { {} }
|
|
72
|
+
|
|
73
|
+
it "skips the batch-loaded fields" do
|
|
74
|
+
expect(result.keys).to eq(%i[first_name link])
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Testing attributes that read the context
|
|
80
|
+
|
|
81
|
+
A context per value of the [context](context.md) shows each outcome:
|
|
82
|
+
|
|
83
|
+
```ruby
|
|
84
|
+
context "#email" do
|
|
85
|
+
let(:selection) { {only: :email} }
|
|
86
|
+
|
|
87
|
+
context "when the user is the current user" do
|
|
88
|
+
let(:context) { {current_user: user} }
|
|
89
|
+
|
|
90
|
+
it "serializes the email" do
|
|
91
|
+
expect(result).to eq(email: "gru@example.com")
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
context "when the user is another user" do
|
|
96
|
+
let(:context) { {current_user: build_stubbed(:user)} }
|
|
97
|
+
|
|
98
|
+
it "skips the email" do
|
|
99
|
+
expect(result).to eq({})
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Moving complex values to their own classes
|
|
106
|
+
|
|
107
|
+
When a `value:` or `batch:` proc grows past a line or two, it can move to its
|
|
108
|
+
own class with its own spec. `:value` and `:batch` accept any object that
|
|
109
|
+
responds to `#call`:
|
|
110
|
+
|
|
111
|
+
```ruby
|
|
112
|
+
class UserLink
|
|
113
|
+
def self.call(user)
|
|
114
|
+
return unless user.username
|
|
115
|
+
|
|
116
|
+
"https://example.com/@#{user.username}"
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The class spec covers the edge cases:
|
|
122
|
+
|
|
123
|
+
```ruby
|
|
124
|
+
RSpec.describe UserLink do
|
|
125
|
+
subject(:link) { described_class.call(user) }
|
|
126
|
+
|
|
127
|
+
let(:user) { build_stubbed(:user, username: username) }
|
|
128
|
+
|
|
129
|
+
context "when the user has a username" do
|
|
130
|
+
let(:username) { "gru" }
|
|
131
|
+
|
|
132
|
+
it "links to the user page" do
|
|
133
|
+
expect(link).to eq("https://example.com/@gru")
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
context "when the user has no username" do
|
|
138
|
+
let(:username) { nil }
|
|
139
|
+
|
|
140
|
+
it "returns nil" do
|
|
141
|
+
expect(link).to be_nil
|
|
142
|
+
end
|
|
143
|
+
end
|
|
144
|
+
end
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
The serializer spec then needs one example that the attribute uses the class:
|
|
148
|
+
|
|
149
|
+
```ruby
|
|
150
|
+
context "#link" do
|
|
151
|
+
let(:selection) { {only: :link} }
|
|
152
|
+
|
|
153
|
+
it "serializes the user link" do
|
|
154
|
+
expect(result).to eq(link: "https://example.com/@gru")
|
|
155
|
+
end
|
|
156
|
+
end
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Testing batch loaders
|
|
160
|
+
|
|
161
|
+
A loader class runs a query, so its spec saves records. A record of a user
|
|
162
|
+
that is not passed to the loader shows that the loader reads only the given
|
|
163
|
+
users:
|
|
164
|
+
|
|
165
|
+
```ruby
|
|
166
|
+
class FollowersCount
|
|
167
|
+
def self.call(users)
|
|
168
|
+
Follow.where(user: users).group(:user_id).count
|
|
169
|
+
end
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
RSpec.describe FollowersCount do
|
|
173
|
+
subject(:counts) { described_class.call(users) }
|
|
174
|
+
|
|
175
|
+
let(:gru) { create(:user) }
|
|
176
|
+
let(:lucy) { create(:user) }
|
|
177
|
+
let(:margo) { create(:user) }
|
|
178
|
+
let(:users) { [gru, lucy] }
|
|
179
|
+
|
|
180
|
+
before do
|
|
181
|
+
create(:follow, user: gru, follower: lucy)
|
|
182
|
+
create(:follow, user: gru, follower: margo)
|
|
183
|
+
create(:follow, user: margo, follower: gru)
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
context "when some users have followers" do
|
|
187
|
+
it "counts the followers of each user" do
|
|
188
|
+
expect(counts).to eq(gru.id => 2)
|
|
189
|
+
end
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Counting queries with ActiveRecord
|
|
195
|
+
|
|
196
|
+
A spec can count the SQL queries of a serialization, to see that
|
|
197
|
+
[preloads](preloads.md) and [batch loaders](batch-loading.md) keep one query
|
|
198
|
+
per relation. A helper in `spec/support` can count them for every spec. It
|
|
199
|
+
skips the schema queries ActiveRecord runs when it first loads a model:
|
|
200
|
+
|
|
201
|
+
```ruby
|
|
202
|
+
# spec/support/count_queries.rb
|
|
203
|
+
module CountQueries
|
|
204
|
+
def count_queries(&block)
|
|
205
|
+
count = 0
|
|
206
|
+
callback = ->(*, payload) { count += 1 unless payload[:name] == "SCHEMA" }
|
|
207
|
+
ActiveSupport::Notifications.subscribed(callback, "sql.active_record", &block)
|
|
208
|
+
count
|
|
209
|
+
end
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
RSpec.configure do |config|
|
|
213
|
+
config.include CountQueries
|
|
214
|
+
end
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
The spec saves records, so the queries run against real data:
|
|
218
|
+
|
|
219
|
+
```ruby
|
|
220
|
+
context "with several users" do
|
|
221
|
+
let!(:users) { create_list(:user, 2) }
|
|
222
|
+
let(:selection) { {only: %i[first_name followers_count]} }
|
|
223
|
+
|
|
224
|
+
it "runs one query for the followers of all users" do
|
|
225
|
+
queries = count_queries { described_class.to_h(users, **selection) }
|
|
226
|
+
|
|
227
|
+
expect(queries).to eq(1)
|
|
228
|
+
end
|
|
229
|
+
end
|
|
230
|
+
```
|
|
@@ -5,17 +5,35 @@ class Serega
|
|
|
5
5
|
# Prepares provided attribute options
|
|
6
6
|
#
|
|
7
7
|
class SeregaAttributeNormalizer # :nodoc:
|
|
8
|
+
# Value of a lazy instance variable that is not prepared yet. The
|
|
9
|
+
# prepared value can be nil or false.
|
|
10
|
+
UNPREPARED = Object.new.freeze
|
|
11
|
+
private_constant :UNPREPARED
|
|
12
|
+
|
|
8
13
|
# Attribute initial params
|
|
9
14
|
attr_reader :init_name, :init_opts, :init_block
|
|
10
15
|
|
|
11
|
-
# Instantiates attribute options normalizer
|
|
16
|
+
# Instantiates attribute options normalizer. The readers prepare their
|
|
17
|
+
# values lazily and call each other in an order that depends on the
|
|
18
|
+
# options, thus every instance variable is declared here, and objects
|
|
19
|
+
# of this class share one shape.
|
|
12
20
|
def initialize(serializer_class, initials)
|
|
13
21
|
@serializer_class = serializer_class
|
|
14
22
|
@init_name = initials[:name]
|
|
15
23
|
@init_opts = initials[:opts]
|
|
16
24
|
@init_block = initials[:block]
|
|
17
|
-
@
|
|
25
|
+
@name = nil
|
|
18
26
|
@key = nil
|
|
27
|
+
@method_name = nil
|
|
28
|
+
@value_block = nil
|
|
29
|
+
@value_block_signature = nil
|
|
30
|
+
@batch_loaders = nil
|
|
31
|
+
@hide = UNPREPARED
|
|
32
|
+
@many = UNPREPARED
|
|
33
|
+
@serializer = UNPREPARED
|
|
34
|
+
@default = UNPREPARED
|
|
35
|
+
@preloads = UNPREPARED
|
|
36
|
+
@batch_option = UNPREPARED
|
|
19
37
|
end
|
|
20
38
|
|
|
21
39
|
# Attribute name, the serialized key as a Symbol
|
|
@@ -46,21 +64,21 @@ class Serega
|
|
|
46
64
|
|
|
47
65
|
# Shows if attribute is specified to be hidden
|
|
48
66
|
def hide
|
|
49
|
-
return @hide
|
|
67
|
+
return @hide unless UNPREPARED.equal?(@hide)
|
|
50
68
|
|
|
51
69
|
@hide = prepare_hide
|
|
52
70
|
end
|
|
53
71
|
|
|
54
72
|
# Shows if attribute is specified to be a one-to-many relationship
|
|
55
73
|
def many
|
|
56
|
-
return @many
|
|
74
|
+
return @many unless UNPREPARED.equal?(@many)
|
|
57
75
|
|
|
58
76
|
@many = prepare_many
|
|
59
77
|
end
|
|
60
78
|
|
|
61
79
|
# Shows specified attribute serializer
|
|
62
80
|
def serializer
|
|
63
|
-
return @serializer
|
|
81
|
+
return @serializer unless UNPREPARED.equal?(@serializer)
|
|
64
82
|
|
|
65
83
|
@serializer = prepare_serializer
|
|
66
84
|
end
|
|
@@ -78,14 +96,14 @@ class Serega
|
|
|
78
96
|
#
|
|
79
97
|
# When custom :default is not specified, we set empty array as default when `many: true` specified
|
|
80
98
|
def default
|
|
81
|
-
return @default
|
|
99
|
+
return @default unless UNPREPARED.equal?(@default)
|
|
82
100
|
|
|
83
101
|
@default = prepare_default
|
|
84
102
|
end
|
|
85
103
|
|
|
86
104
|
# Preloads declared for this attribute, passed through as provided.
|
|
87
105
|
def preloads
|
|
88
|
-
return @preloads
|
|
106
|
+
return @preloads unless UNPREPARED.equal?(@preloads)
|
|
89
107
|
|
|
90
108
|
@preloads = prepare_preloads
|
|
91
109
|
end
|
|
@@ -221,7 +239,7 @@ class Serega
|
|
|
221
239
|
|
|
222
240
|
# The parsed :batch option, `nil` without it
|
|
223
241
|
def batch_option
|
|
224
|
-
return @batch_option
|
|
242
|
+
return @batch_option unless UNPREPARED.equal?(@batch_option)
|
|
225
243
|
|
|
226
244
|
batch = init_opts[:batch]
|
|
227
245
|
@batch_option = batch && AttributeNormalizers::Batch.new(batch, name)
|
|
@@ -71,9 +71,9 @@ class Serega
|
|
|
71
71
|
return base_serializer if base_serializer
|
|
72
72
|
|
|
73
73
|
raise SeregaError,
|
|
74
|
-
"Attribute block requires a base serializer for the nested serializer
|
|
75
|
-
"
|
|
76
|
-
" or set `config.base_serializer = <
|
|
74
|
+
"Attribute block requires a base serializer for the nested serializer\n" \
|
|
75
|
+
"(hint: provide the `base_serializer: <BaseSerializer>` attribute option" \
|
|
76
|
+
" or set `config.base_serializer = <BaseSerializer>`)"
|
|
77
77
|
end
|
|
78
78
|
end
|
|
79
79
|
end
|
data/lib/serega/config.rb
CHANGED
|
@@ -23,7 +23,7 @@ class Serega
|
|
|
23
23
|
serialize_keys: %i[context many].freeze,
|
|
24
24
|
check_attribute_name: true,
|
|
25
25
|
require_many: false,
|
|
26
|
-
|
|
26
|
+
many: nil,
|
|
27
27
|
delegate_default_allow_nil: false,
|
|
28
28
|
max_cached_plans_per_serializer_count: 20,
|
|
29
29
|
depth_limit: nil,
|
|
@@ -34,7 +34,8 @@ class Serega
|
|
|
34
34
|
key_transform: nil,
|
|
35
35
|
batch_id_option: :id,
|
|
36
36
|
base_serializer: nil,
|
|
37
|
-
hash_access: {default_mode: :symbol, default_allow_missing_key: false}
|
|
37
|
+
hash_access: {default_mode: :symbol, default_allow_missing_key: false},
|
|
38
|
+
deprecation_warnings: true
|
|
38
39
|
}.freeze
|
|
39
40
|
# :nocov:
|
|
40
41
|
|
|
@@ -61,17 +62,6 @@ class Serega
|
|
|
61
62
|
opts.fetch(:serialize_keys)
|
|
62
63
|
end
|
|
63
64
|
|
|
64
|
-
# Whether unknown fields of `only:`, `except:` and `with:` raise
|
|
65
|
-
# `Serega::AttributeNotExist`. `true` by default.
|
|
66
|
-
def check_selection
|
|
67
|
-
opts.fetch(:check_selection)
|
|
68
|
-
end
|
|
69
|
-
|
|
70
|
-
# Sets #check_selection
|
|
71
|
-
def check_selection=(value)
|
|
72
|
-
opts[:check_selection] = checked_boolean(value)
|
|
73
|
-
end
|
|
74
|
-
|
|
75
65
|
# Default `allow_nil:` of the `:delegate` attribute option. `false` by
|
|
76
66
|
# default.
|
|
77
67
|
def delegate_default_allow_nil
|
|
@@ -144,6 +134,17 @@ class Serega
|
|
|
144
134
|
opts[:compact] = checked_boolean(value)
|
|
145
135
|
end
|
|
146
136
|
|
|
137
|
+
# Whether loading a deprecated plugin prints a warning. `true` by
|
|
138
|
+
# default.
|
|
139
|
+
def deprecation_warnings
|
|
140
|
+
opts.fetch(:deprecation_warnings)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# Sets #deprecation_warnings
|
|
144
|
+
def deprecation_warnings=(value)
|
|
145
|
+
opts[:deprecation_warnings] = checked_boolean(value)
|
|
146
|
+
end
|
|
147
|
+
|
|
147
148
|
# How attribute names become serialized keys: `nil` (names as they are,
|
|
148
149
|
# the default), `:camel_case` (`first_name` gives `firstName`), or a
|
|
149
150
|
# callable that receives the name Symbol and returns the key. A String
|
|
@@ -239,6 +240,20 @@ class Serega
|
|
|
239
240
|
opts[:require_many] = checked_boolean(value)
|
|
240
241
|
end
|
|
241
242
|
|
|
243
|
+
# How a call without the `:many` option serializes the object: `true` as a
|
|
244
|
+
# list, `false` as one object. `nil`, the default, serializes an
|
|
245
|
+
# `Enumerable` that is not a `Hash` or `Struct` as a list.
|
|
246
|
+
def many
|
|
247
|
+
opts.fetch(:many)
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
# Sets #many
|
|
251
|
+
def many=(value)
|
|
252
|
+
raise SeregaError, "Must have true, false or nil, #{value.inspect} provided" unless value.nil? || value == true || value == false
|
|
253
|
+
|
|
254
|
+
opts[:many] = value
|
|
255
|
+
end
|
|
256
|
+
|
|
242
257
|
# Method that returns the id of an object for batch loaders, `:id` by
|
|
243
258
|
# default
|
|
244
259
|
def batch_id_option
|
data/lib/serega/errors.rb
CHANGED
|
@@ -36,7 +36,7 @@ class Serega
|
|
|
36
36
|
# # => Serega::PresetNotExist: Preset :admin is not defined in UserSerializer
|
|
37
37
|
# ```
|
|
38
38
|
#
|
|
39
|
-
# See [Presets](https://github.com/andreyruby/serega/blob/master/docs/
|
|
39
|
+
# See [Presets](https://github.com/andreyruby/serega/blob/master/docs/presets.md).
|
|
40
40
|
class PresetNotExist < SeregaError
|
|
41
41
|
# Serializer that has no such preset
|
|
42
42
|
attr_reader :serializer
|
|
@@ -60,7 +60,7 @@ class Serega
|
|
|
60
60
|
# # => Serega::DepthLimitError: Depth limit was exceeded
|
|
61
61
|
# ```
|
|
62
62
|
#
|
|
63
|
-
# See [
|
|
63
|
+
# See [Limiting nesting depth](https://github.com/andreyruby/serega/blob/master/docs/relations.md#limiting-nesting-depth).
|
|
64
64
|
class DepthLimitError < SeregaError
|
|
65
65
|
# Path that exceeds the limit or closes the cycle, and on the next line a hint:
|
|
66
66
|
#
|