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.
- 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 +5 -4
- data/lib/serega/plan/cache.rb +13 -29
- data/lib/serega/plan/depth_limit.rb +27 -8
- data/lib/serega/plan/per_ractor_cache.rb +2 -2
- data/lib/serega/plan/point.rb +13 -2
- data/lib/serega/plan/selection.rb +10 -0
- data/lib/serega/plan.rb +7 -3
- 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 +2 -2
- 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 +54 -46
- data/sig/serega.rbs +10 -8
- metadata +30 -6
data/docs/camel-case.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# camelCase Keys
|
|
2
|
+
|
|
3
|
+
`config.key_transform = :camel_case` serializes `first_name` as `firstName`.
|
|
4
|
+
Set it in a base serializer to change the keys of all serializers:
|
|
5
|
+
|
|
6
|
+
```ruby
|
|
7
|
+
class AppSerializer < Serega
|
|
8
|
+
config.key_transform = :camel_case
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
class PostSerializer < AppSerializer
|
|
12
|
+
attribute :post_title
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
class UserSerializer < AppSerializer
|
|
16
|
+
attribute :first_name
|
|
17
|
+
attribute :recent_posts, serializer: PostSerializer, many: true
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
UserSerializer.to_h(user)
|
|
21
|
+
# => {firstName: "Felonious", recentPosts: [{postTitle: "Stealing the Moon"}]}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Table of Contents
|
|
25
|
+
|
|
26
|
+
<!-- toc -->
|
|
27
|
+
|
|
28
|
+
- [Values come from the original names](#values-come-from-the-original-names)
|
|
29
|
+
- [Fields are selected by the new keys](#fields-are-selected-by-the-new-keys)
|
|
30
|
+
- [One camelCase key](#one-camelcase-key)
|
|
31
|
+
- [Other key styles](#other-key-styles)
|
|
32
|
+
- [When the transformation runs](#when-the-transformation-runs)
|
|
33
|
+
|
|
34
|
+
<!-- tocstop -->
|
|
35
|
+
|
|
36
|
+
## Values come from the original names
|
|
37
|
+
|
|
38
|
+
The key changes, the source does not: `first_name` still reads
|
|
39
|
+
`user.first_name`, and with [`hash_access`](hash-records.md) it reads
|
|
40
|
+
`record[:first_name]`. Options that name a method, such as `:method` and
|
|
41
|
+
`:delegate`, keep the Ruby names too.
|
|
42
|
+
|
|
43
|
+
## Fields are selected by the new keys
|
|
44
|
+
|
|
45
|
+
`only:`, `except:`, `with:`, presets, `.attributes` and the members of
|
|
46
|
+
`.to_struct` and `.to_data` use the camelCase keys, as clients see them:
|
|
47
|
+
|
|
48
|
+
```ruby
|
|
49
|
+
UserSerializer.to_h(user, only: "firstName,recentPosts(postTitle)")
|
|
50
|
+
# => {firstName: "Felonious", recentPosts: [{postTitle: "Stealing the Moon"}]}
|
|
51
|
+
|
|
52
|
+
preset :card, only: [:firstName, {recentPosts: :postTitle}] # in UserSerializer
|
|
53
|
+
|
|
54
|
+
UserSerializer.attributes.keys # => [:firstName, :recentPosts]
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## One camelCase key
|
|
58
|
+
|
|
59
|
+
Without `key_transform`, the attribute name is the key as is. A single
|
|
60
|
+
camelCase key reads its value with `:method`:
|
|
61
|
+
|
|
62
|
+
```ruby
|
|
63
|
+
attribute :firstName, method: :first_name
|
|
64
|
+
# => {firstName: "Felonious"}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Other key styles
|
|
68
|
+
|
|
69
|
+
A callable receives the name as a Symbol and returns the key. A String key
|
|
70
|
+
stays a String in the serialized Hash:
|
|
71
|
+
|
|
72
|
+
```ruby
|
|
73
|
+
config.key_transform = ->(name) { name.to_s.camelize(:lower) } # ActiveSupport
|
|
74
|
+
# => {"firstName" => "Felonious"}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Fields are still selected by the keys as Symbols: `only: :firstName`.
|
|
78
|
+
|
|
79
|
+
## When the transformation runs
|
|
80
|
+
|
|
81
|
+
`key_transform` changes the names of the attributes defined after it, so set
|
|
82
|
+
it before the attributes, in a base serializer. A related serializer uses its
|
|
83
|
+
own config, thus it needs the same base serializer.
|
|
84
|
+
|
|
85
|
+
The transformation runs once, when an attribute is defined, thus it costs
|
|
86
|
+
nothing during serialization.
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# Conditional Attributes
|
|
2
|
+
|
|
3
|
+
`:if` and `:unless` skip an attribute depending on the serialized object.
|
|
4
|
+
`:if_value` and `:unless_value` skip it depending on its value.
|
|
5
|
+
|
|
6
|
+
```ruby
|
|
7
|
+
class UserSerializer < Serega
|
|
8
|
+
attribute :email, if: :active? # user.active?
|
|
9
|
+
attribute :phone, if: proc { |user, ctx| ctx[:admin] }
|
|
10
|
+
attribute :role, unless: proc { |user, ctx:| ctx[:public] }
|
|
11
|
+
attribute :nickname, if_value: proc { |nickname| !nickname.nil? }
|
|
12
|
+
attribute :rating, unless_value: :zero? # rating.zero?
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
UserSerializer.to_h(user, context: {admin: true})
|
|
16
|
+
# => {email: "gru@example.com", phone: "555-0100", role: "admin", rating: 5}
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Table of Contents
|
|
20
|
+
|
|
21
|
+
<!-- toc -->
|
|
22
|
+
|
|
23
|
+
- [Conditions](#conditions)
|
|
24
|
+
- [Order of checks](#order-of-checks)
|
|
25
|
+
- [Conditions on relations](#conditions-on-relations)
|
|
26
|
+
- [Conditions that load data](#conditions-that-load-data)
|
|
27
|
+
- [Skipped attributes in results](#skipped-attributes-in-results)
|
|
28
|
+
- [Leaving out nil values](#leaving-out-nil-values)
|
|
29
|
+
- [Finding a failing condition](#finding-a-failing-condition)
|
|
30
|
+
|
|
31
|
+
<!-- tocstop -->
|
|
32
|
+
|
|
33
|
+
## Conditions
|
|
34
|
+
|
|
35
|
+
A condition is one of:
|
|
36
|
+
|
|
37
|
+
- a method name, called on the object (`:if`, `:unless`) or on the value
|
|
38
|
+
(`:if_value`, `:unless_value`);
|
|
39
|
+
- a callable that receives the object or the value, and the
|
|
40
|
+
[context](context.md) as a second parameter or as the `:ctx` keyword.
|
|
41
|
+
|
|
42
|
+
```ruby
|
|
43
|
+
attribute :email, if: proc { |user, ctx| user == ctx[:current_user] }
|
|
44
|
+
attribute :email, if: EmailPolicy.method(:visible?) # EmailPolicy.visible?(user)
|
|
45
|
+
attribute :email, if_value: proc { |email, ctx| ctx[:show_emails] }
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Order of checks
|
|
49
|
+
|
|
50
|
+
`:if` and `:unless` are checked before the value is found, so a skipped
|
|
51
|
+
attribute does not compute its value. `:if_value` and `:unless_value` are
|
|
52
|
+
checked after.
|
|
53
|
+
|
|
54
|
+
`:unless` is checked only when `:if` passes, and `:unless_value` only when
|
|
55
|
+
`:if_value` passes.
|
|
56
|
+
|
|
57
|
+
## Conditions on relations
|
|
58
|
+
|
|
59
|
+
`:if` and `:unless` skip a relation before its related objects are
|
|
60
|
+
serialized. `:if_value` and `:unless_value` check the serialized relation
|
|
61
|
+
value: a Hash, an Array of Hashes or `nil`, or `Struct` and `Data` objects with
|
|
62
|
+
`.to_struct` and `.to_data`. The related objects are serialized before this
|
|
63
|
+
check, thus prefer `:if` and `:unless` when the object decides.
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
class UserSerializer < Serega
|
|
67
|
+
attribute :posts, serializer: PostSerializer, many: true, unless_value: :empty?
|
|
68
|
+
attribute :avatar, serializer: AvatarSerializer, unless_value: :nil?
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
UserSerializer.to_h(user) # a user without posts and avatar
|
|
72
|
+
# => {}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Without a condition, a relation keeps its key: a `nil` related object
|
|
76
|
+
serializes as `{avatar: nil}`, and `many: true` serializes `nil` as `[]`.
|
|
77
|
+
|
|
78
|
+
## Conditions that load data
|
|
79
|
+
|
|
80
|
+
A condition runs once per object, thus a query inside it runs once per object
|
|
81
|
+
too. Load the data for all objects at once instead.
|
|
82
|
+
|
|
83
|
+
An association: [preload](preloads.md) it, and read it in `:if`.
|
|
84
|
+
|
|
85
|
+
```ruby
|
|
86
|
+
class UserSerializer < Serega
|
|
87
|
+
plugin :activerecord_preloads
|
|
88
|
+
|
|
89
|
+
attribute :email, preload: :privacy_setting, if: proc { |user| user.privacy_setting.public_email }
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
UserSerializer.to_h(users)
|
|
93
|
+
# SELECT * FROM privacy_settings WHERE user_id IN (1, 2)
|
|
94
|
+
# => [{email: "gru@example.com"}, {}]
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Other data: load it with a [batch loader](batch-loading.md), build `nil` in
|
|
98
|
+
`:value` for a hidden object, and skip `nil` with `:unless_value`.
|
|
99
|
+
|
|
100
|
+
```ruby
|
|
101
|
+
class UserSerializer < Serega
|
|
102
|
+
batch :visible_user_ids, ->(users, ctx:) { ctx[:viewer].visible_users.where(id: users).pluck(:id).to_set }
|
|
103
|
+
|
|
104
|
+
attribute :email, batch: {use: :visible_user_ids}, unless_value: :nil?,
|
|
105
|
+
value: proc { |user, batches:| user.email if batches[:visible_user_ids].include?(user.id) }
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
UserSerializer.to_h(users, context: {viewer: current_user})
|
|
109
|
+
# SELECT id FROM users WHERE ... AND id IN (1, 2)
|
|
110
|
+
# => [{email: "gru@example.com"}, {}]
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The batch way skips the attribute for a `nil` email of a visible user too. A
|
|
114
|
+
relation works the same way: `:value` gives `nil` for a hidden object, and
|
|
115
|
+
`unless_value: :nil?` skips the relation.
|
|
116
|
+
|
|
117
|
+
## Skipped attributes in results
|
|
118
|
+
|
|
119
|
+
`.to_h` omits skipped attributes. `.to_struct` and `.to_data` return `nil` for
|
|
120
|
+
them, so all objects serialized with the same fields have the same members.
|
|
121
|
+
|
|
122
|
+
```ruby
|
|
123
|
+
UserSerializer.to_h(user, context: {public: true})
|
|
124
|
+
# => {email: "gru@example.com", rating: 5}
|
|
125
|
+
|
|
126
|
+
UserSerializer.to_struct(user, context: {public: true})
|
|
127
|
+
# => #<struct email="gru@example.com", phone=nil, role=nil, nickname=nil, rating=5>
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Leaving out nil values
|
|
131
|
+
|
|
132
|
+
`config.compact = true` leaves out every key with a `nil` value, as
|
|
133
|
+
`Hash#compact` does. Set it in a base serializer to compact whole responses,
|
|
134
|
+
nested serializers included:
|
|
135
|
+
|
|
136
|
+
```ruby
|
|
137
|
+
class AppSerializer < Serega
|
|
138
|
+
config.compact = true
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
class UserSerializer < AppSerializer
|
|
142
|
+
attribute :first_name
|
|
143
|
+
attribute :nickname
|
|
144
|
+
attribute :posts, serializer: PostSerializer, many: true
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
UserSerializer.to_h(user) # a user without a nickname and posts
|
|
148
|
+
# => {first_name: "Felonious", posts: []}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
A nested serializer follows its own config: one without `compact` keeps its
|
|
152
|
+
`nil` values. Empty Strings, Arrays and Hashes stay, and `nil` items inside an
|
|
153
|
+
Array stay too. `.to_struct` and `.to_data` keep `nil` members.
|
|
154
|
+
|
|
155
|
+
## Finding a failing condition
|
|
156
|
+
|
|
157
|
+
An error raised by a condition names the condition and the line where the
|
|
158
|
+
attribute is defined:
|
|
159
|
+
|
|
160
|
+
```text
|
|
161
|
+
(when checking the :if condition of the 'email' attribute in UserSerializer, app/serializers/user_serializer.rb:4)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
To hide an attribute unless a client requests it, use `hide: true`, see
|
|
165
|
+
[Selecting fields](selecting-fields.md).
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Configuration
|
|
2
|
+
|
|
3
|
+
Set config in a base serializer. Child serializers inherit it and can change
|
|
4
|
+
it.
|
|
5
|
+
|
|
6
|
+
```ruby
|
|
7
|
+
class AppSerializer < Serega
|
|
8
|
+
config.auto_preload = true
|
|
9
|
+
config.hide_by_default = :auto
|
|
10
|
+
config.base_serializer = self
|
|
11
|
+
end
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Set config before defining attributes. An attribute reads the config when it is
|
|
15
|
+
defined, so a later change to `auto_preload`, `hide_by_default`,
|
|
16
|
+
`key_transform`, `batch_id_option` or `base_serializer` affects only attributes
|
|
17
|
+
defined after it.
|
|
18
|
+
|
|
19
|
+
## Options
|
|
20
|
+
|
|
21
|
+
| Option | Default | Description |
|
|
22
|
+
|---|---|---|
|
|
23
|
+
| `auto_preload` | `false` | Adds [preloads][automatic-preloads] to `:delegate` and `:serializer` attributes |
|
|
24
|
+
| `auto_preload_excluded_methods` | `[:itself, :__getobj__]` | Methods never preloaded automatically |
|
|
25
|
+
| `hide_by_default` | `false` | Hides attributes, see [Hiding by default](selecting-fields.md#hiding-by-default) |
|
|
26
|
+
| `key_transform` | `nil` | Changes attribute keys, see [camelCase and other key styles][key-styles] |
|
|
27
|
+
| `compact` | `false` | [Leaves out keys with `nil` values](conditional-attributes.md#leaving-out-nil-values) |
|
|
28
|
+
| `base_serializer` | `nil` | Superclass of [block-defined serializers][block-serializers] |
|
|
29
|
+
| `batch_id_option` | `:id` | Method that returns the id of an object for [batch loaders][batch-ids] |
|
|
30
|
+
| `delegate_default_allow_nil` | `false` | Default `allow_nil:` of [delegates](attributes.md#delegate) |
|
|
31
|
+
| `hash_access.default_mode` | `:symbol` | Mode of `hash_access: true`. See [Hash records][hash-mode] |
|
|
32
|
+
| `hash_access.default_allow_missing_key` | `false` | `nil` for missing Hash keys |
|
|
33
|
+
| `check_attribute_name` | `true` | Allows only `a-z`, `A-Z`, `0-9`, `_`, `-`, `~` in attribute names |
|
|
34
|
+
| `require_many` | `false` | Requires [`:many`](relations.md#many) on relations |
|
|
35
|
+
| `many` | `nil` | Serializes as a list (`true`) or one object (`false`) without a `:many` option; `nil` detects lists |
|
|
36
|
+
| `max_cached_plans_per_serializer_count` | `20` | [Plans cached][plan-cache] per serializer, `0` disables the cache |
|
|
37
|
+
| `depth_limit` | `nil` | Deepest nesting of serialized fields, see [Limiting nesting depth][depth-limit] |
|
|
38
|
+
| `deprecation_warnings` | `true` | Warns when a [deprecated plugin][root-metadata] loads |
|
|
39
|
+
|
|
40
|
+
[automatic-preloads]: preloads.md#automatic-preloads
|
|
41
|
+
[root-metadata]: root-and-metadata.md
|
|
42
|
+
[block-serializers]: relations.md#nested-serializers-defined-with-a-block
|
|
43
|
+
[key-styles]: camel-case.md
|
|
44
|
+
[batch-ids]: batch-loading.md#records-without-an-id
|
|
45
|
+
[hash-mode]: hash-records.md#default-access-mode
|
|
46
|
+
[plan-cache]: serializing.md#plan-cache
|
|
47
|
+
[depth-limit]: relations.md#limiting-nesting-depth
|
data/docs/context.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Context
|
|
2
|
+
|
|
3
|
+
The context passes request data, like the current user, to a serialization.
|
|
4
|
+
|
|
5
|
+
```ruby
|
|
6
|
+
class UserSerializer < Serega
|
|
7
|
+
attribute :email, value: proc { |user, ctx| user.email if user == ctx[:current_user] }
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
UserSerializer.to_h(user, context: {current_user: user})
|
|
11
|
+
# => {email: "gru@example.com"}
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The context is available as a second parameter or as the `:ctx` keyword in:
|
|
15
|
+
|
|
16
|
+
- [`:value`](attributes.md#value) callables;
|
|
17
|
+
- [`:if` and `:unless`](conditional-attributes.md) conditions;
|
|
18
|
+
- [formatters](formatters.md);
|
|
19
|
+
- [batch loaders](batch-loading.md);
|
|
20
|
+
- [`prepare_initial_objects`](prepare-initial-objects.md) handlers.
|
|
21
|
+
|
|
22
|
+
```ruby
|
|
23
|
+
class UserSerializer < Serega
|
|
24
|
+
formatter :masked, ->(email, ctx) { ctx[:admin] ? email : "***" }
|
|
25
|
+
batch :badges, ->(users, ctx:) { Badge.for(users, season: ctx[:season]) }
|
|
26
|
+
|
|
27
|
+
attribute :email, format: :masked
|
|
28
|
+
attribute :phone, if: proc { |user, ctx| ctx[:admin] }
|
|
29
|
+
attribute :badge, batch: :badges
|
|
30
|
+
end
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Serega passes the given context as is. Without the `:context` option, the
|
|
34
|
+
context is a frozen empty Hash.
|
data/docs/errors.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Errors
|
|
2
|
+
|
|
3
|
+
| Error | Raised when |
|
|
4
|
+
|---|---|
|
|
5
|
+
| `Serega::SeregaError` | Invalid definitions, options or changes to locked serializers. Base class of other errors |
|
|
6
|
+
| `Serega::AttributeNotExist` | `:only`, `:except`, `:with` or a preset lists an unknown field |
|
|
7
|
+
| `Serega::PresetNotExist` | `:preset` names an undefined preset |
|
|
8
|
+
| `Serega::DepthLimitError` | Fields nest deeper than [`config.depth_limit`][depth_limit], or relations in a cycle |
|
|
9
|
+
|
|
10
|
+
`Serega::AttributeNotExist#serializer` returns the serializer and `#attributes`
|
|
11
|
+
returns the unknown fields. See [Selecting fields](selecting-fields.md#unknown-fields).
|
|
12
|
+
|
|
13
|
+
`Serega::PresetNotExist#serializer` returns the serializer and `#preset`
|
|
14
|
+
returns the name of the undefined preset. See [Presets](presets.md).
|
|
15
|
+
|
|
16
|
+
## Errors in attributes
|
|
17
|
+
|
|
18
|
+
Serega keeps the class of an error raised while serializing an attribute, and
|
|
19
|
+
adds the attribute, the serializer and the line where the attribute is
|
|
20
|
+
defined to its message:
|
|
21
|
+
|
|
22
|
+
```text
|
|
23
|
+
NoMethodError: undefined method 'city' for nil
|
|
24
|
+
(when serializing the 'city' attribute in UserSerializer, app/serializers/user_serializer.rb:5)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The backtrace has a line at the attribute too, below the line that raised:
|
|
28
|
+
|
|
29
|
+
```text
|
|
30
|
+
app/models/user.rb:12:in 'User#address'
|
|
31
|
+
app/serializers/user_serializer.rb:5:in 'attribute :city of UserSerializer'
|
|
32
|
+
(serega generated code):20:in 'call'
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Errors raised by [conditions](conditional-attributes.md#finding-a-failing-condition) name the
|
|
36
|
+
condition too.
|
|
37
|
+
|
|
38
|
+
[depth_limit]: relations.md#limiting-nesting-depth
|
data/docs/formatters.md
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# Formatters
|
|
2
|
+
|
|
3
|
+
Formatters format dates, money and other values the same way in every
|
|
4
|
+
serializer. Named formatters, defined for example in a base serializer, are
|
|
5
|
+
used with the `:format` attribute option.
|
|
6
|
+
|
|
7
|
+
```ruby
|
|
8
|
+
class AppSerializer < Serega
|
|
9
|
+
formatter :iso8601, [:iso8601, 3], allow_nil: true
|
|
10
|
+
formatter :money, ->(cents, ctx) { "#{(cents / 100.0).round(2)} #{ctx[:currency]}" }
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
class OrderSerializer < AppSerializer
|
|
14
|
+
attribute :created_at, format: :iso8601
|
|
15
|
+
attribute :total_cents, format: :money
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
OrderSerializer.to_h(order, context: {currency: "EUR"})
|
|
19
|
+
# => {created_at: "2026-10-18T12:30:15.000Z", total_cents: "19.99 EUR"}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Child serializers get the formatters of their parents. Define a formatter
|
|
23
|
+
before the attributes that use it: `format: :money` with no `:money`
|
|
24
|
+
formatter defined yet raises `Serega::SeregaError`.
|
|
25
|
+
|
|
26
|
+
## Table of Contents
|
|
27
|
+
|
|
28
|
+
<!-- toc -->
|
|
29
|
+
|
|
30
|
+
- [Formatter kinds](#formatter-kinds)
|
|
31
|
+
- [Formatters without a name](#formatters-without-a-name)
|
|
32
|
+
- [Common formatters](#common-formatters)
|
|
33
|
+
- [Times for JavaScript clients (`:iso8601`)](#times-for-javascript-clients-iso8601)
|
|
34
|
+
- [Dates (`:date`)](#dates-date)
|
|
35
|
+
- [Decimals as JSON numbers (`:float`)](#decimals-as-json-numbers-float)
|
|
36
|
+
- [Rounding (`:round2`)](#rounding-round2)
|
|
37
|
+
- [Percents (`:percent`)](#percents-percent)
|
|
38
|
+
- [Blank strings as `nil` (`:presence`)](#blank-strings-as-nil-presence)
|
|
39
|
+
- [API type names (`:type`)](#api-type-names-type)
|
|
40
|
+
- [Money (`:money`)](#money-money)
|
|
41
|
+
- [Decimals in JSON](#decimals-in-json)
|
|
42
|
+
- [Formatting `nil` values](#formatting-nil-values)
|
|
43
|
+
|
|
44
|
+
<!-- tocstop -->
|
|
45
|
+
|
|
46
|
+
## Formatter kinds
|
|
47
|
+
|
|
48
|
+
```ruby
|
|
49
|
+
class AppSerializer < Serega
|
|
50
|
+
# A method name: value.to_s
|
|
51
|
+
formatter :string, :to_s
|
|
52
|
+
|
|
53
|
+
# A method name with arguments: value.iso8601(3)
|
|
54
|
+
formatter :iso8601, [:iso8601, 3]
|
|
55
|
+
|
|
56
|
+
# An operator is a method too: value * 100
|
|
57
|
+
formatter :percent, [:*, 100]
|
|
58
|
+
|
|
59
|
+
# A callable with the value
|
|
60
|
+
formatter :yes_no, ->(value) { value ? "yes" : "no" }
|
|
61
|
+
|
|
62
|
+
# A callable with the value and the context, as a second parameter or the :ctx keyword
|
|
63
|
+
formatter :money, ->(cents, ctx) { "#{cents / 100.0} #{ctx[:currency]}" }
|
|
64
|
+
formatter :price, ->(cents, ctx:) { "#{cents / 100.0} #{ctx[:currency]}" }
|
|
65
|
+
|
|
66
|
+
# A block
|
|
67
|
+
formatter(:upcase) { |value| value.upcase }
|
|
68
|
+
end
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
A Symbol or an Array in a formatter is a plain Ruby method of the value, with
|
|
72
|
+
its arguments: `:to_s` calls `value.to_s`, and `[:iso8601, 3]` calls
|
|
73
|
+
`Time#iso8601(3)`. Serega adds no formatting methods of its own, so any method
|
|
74
|
+
of the value works, from Ruby, ActiveSupport or your own classes.
|
|
75
|
+
|
|
76
|
+
A method formatter is called directly in the generated serialization code,
|
|
77
|
+
which makes it the fastest kind.
|
|
78
|
+
|
|
79
|
+
## Formatters without a name
|
|
80
|
+
|
|
81
|
+
`:format` also accepts a formatter directly. A Symbol is always a formatter
|
|
82
|
+
name, so a method name alone needs a named formatter.
|
|
83
|
+
|
|
84
|
+
```ruby
|
|
85
|
+
attribute :rating, format: [:round, 1]
|
|
86
|
+
attribute :email, format: ->(email) { email.downcase }
|
|
87
|
+
attribute :nickname, format: {use: :upcase, allow_nil: true}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Common formatters
|
|
91
|
+
|
|
92
|
+
Examples of formatters that many APIs use. Copy the ones you need, for
|
|
93
|
+
example into a base serializer, and change them as you like. The names, such
|
|
94
|
+
as `:round2`, are yours to choose. The methods they call are Ruby's:
|
|
95
|
+
`Time#iso8601`, `Date#iso8601`, `BigDecimal#to_f`, `Float#round` and
|
|
96
|
+
ActiveSupport's `Object#presence`.
|
|
97
|
+
|
|
98
|
+
### Times for JavaScript clients (`:iso8601`)
|
|
99
|
+
|
|
100
|
+
JavaScript dates resolve to milliseconds, so three fraction digits are enough.
|
|
101
|
+
|
|
102
|
+
```ruby
|
|
103
|
+
formatter :iso8601, [:iso8601, 3], allow_nil: true
|
|
104
|
+
|
|
105
|
+
attribute :created_at, format: :iso8601
|
|
106
|
+
# Time.utc(2026, 11, 16, 10, 30, 15.123456) => "2026-11-16T10:30:15.123Z"
|
|
107
|
+
# nil => nil
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### Dates (`:date`)
|
|
111
|
+
|
|
112
|
+
```ruby
|
|
113
|
+
formatter :date, :iso8601, allow_nil: true
|
|
114
|
+
|
|
115
|
+
attribute :birthday, format: :date
|
|
116
|
+
# Date.new(2026, 11, 16) => "2026-11-16"
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Decimals as JSON numbers (`:float`)
|
|
120
|
+
|
|
121
|
+
Decimal columns return a `BigDecimal`, which JSON writes as a String, see
|
|
122
|
+
[Decimals in JSON](#decimals-in-json).
|
|
123
|
+
|
|
124
|
+
```ruby
|
|
125
|
+
formatter :float, :to_f, allow_nil: true
|
|
126
|
+
|
|
127
|
+
attribute :latitude, format: :float
|
|
128
|
+
# BigDecimal("51.501364") => 51.501364
|
|
129
|
+
# nil => nil
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Rounding (`:round2`)
|
|
133
|
+
|
|
134
|
+
```ruby
|
|
135
|
+
formatter :round2, [:round, 2]
|
|
136
|
+
|
|
137
|
+
attribute :ratio, format: :round2
|
|
138
|
+
# 12.345 => 12.35
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Percents (`:percent`)
|
|
142
|
+
|
|
143
|
+
```ruby
|
|
144
|
+
formatter :percent, ->(fraction) { (fraction * 100).round(2) }
|
|
145
|
+
|
|
146
|
+
attribute :conversion, format: :percent
|
|
147
|
+
# 0.125 => 12.5
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Blank strings as `nil` (`:presence`)
|
|
151
|
+
|
|
152
|
+
`Object#presence` comes from ActiveSupport.
|
|
153
|
+
|
|
154
|
+
```ruby
|
|
155
|
+
formatter :presence, :presence
|
|
156
|
+
|
|
157
|
+
attribute :bio, format: :presence
|
|
158
|
+
# "" => nil
|
|
159
|
+
# "Freedonia" => "Freedonia"
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### API type names (`:type`)
|
|
163
|
+
|
|
164
|
+
Clients that store records by type and id need a type in every record. A
|
|
165
|
+
constant attribute holds the model, and the formatter names its type. The
|
|
166
|
+
formatter takes a class or a class name, so it also names the type of a
|
|
167
|
+
polymorphic `*_type` column.
|
|
168
|
+
|
|
169
|
+
```ruby
|
|
170
|
+
TYPES = {"User" => "users", "Post" => "posts"}.freeze
|
|
171
|
+
formatter :type, ->(model) { TYPES.fetch(model.to_s) }
|
|
172
|
+
|
|
173
|
+
attribute :type, const: User, format: :type
|
|
174
|
+
# User => "users"
|
|
175
|
+
|
|
176
|
+
attribute :commentable_type, format: :type
|
|
177
|
+
# "Post" => "posts"
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`TYPES.fetch` raises `KeyError` for a model without a type, so a new model
|
|
181
|
+
can't send a wrong one. The Hash keeps API type names apart from class names:
|
|
182
|
+
renaming a model doesn't change the API, and `TYPES.invert` turns a type from
|
|
183
|
+
a request back into a class name.
|
|
184
|
+
|
|
185
|
+
### Money (`:money`)
|
|
186
|
+
|
|
187
|
+
Money in cents, without trailing zeros. A formatter that depends on the
|
|
188
|
+
locale or the currency fits a callable class:
|
|
189
|
+
`formatter :money, MoneyFormatter.new`.
|
|
190
|
+
|
|
191
|
+
```ruby
|
|
192
|
+
formatter :money, ->(cents) { format("$%.2f", cents / 100.0).delete_suffix(".00") }
|
|
193
|
+
|
|
194
|
+
attribute :price_cents, format: :money
|
|
195
|
+
# 1999 => "$19.99"
|
|
196
|
+
# 2000 => "$20"
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Decimals in JSON
|
|
200
|
+
|
|
201
|
+
Serega returns a `BigDecimal` as is, and `to_json` writes it with
|
|
202
|
+
`JSON.generate`. Without ActiveSupport this writes it as a String in
|
|
203
|
+
scientific notation: `"0.51501364e2"`. With ActiveSupport, as in Rails, it
|
|
204
|
+
writes `"51.501364"`. A formatter gives the same output in both cases.
|
|
205
|
+
|
|
206
|
+
```ruby
|
|
207
|
+
class PlaceSerializer < Serega
|
|
208
|
+
# JSON numbers: value.to_f
|
|
209
|
+
attribute :latitude, format: [:to_f]
|
|
210
|
+
attribute :longitude, format: [:to_f]
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
PlaceSerializer.to_json(place)
|
|
214
|
+
# => "{\"latitude\":51.501364,\"longitude\":-0.14189}"
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
A Float keeps about 17 significant digits, thus `to_f` rounds longer decimals:
|
|
218
|
+
`BigDecimal("12345678901234567.89").to_f` is `1.2345678901234568e+16`. For a
|
|
219
|
+
String with every digit, use `format: [:to_s, "F"]`.
|
|
220
|
+
|
|
221
|
+
## Formatting `nil` values
|
|
222
|
+
|
|
223
|
+
A formatter formats `nil` too: a callable receives `nil`, and a method is
|
|
224
|
+
called on `nil`. With `allow_nil: true` a `nil` value stays `nil`.
|
|
225
|
+
|
|
226
|
+
```ruby
|
|
227
|
+
formatter :iso8601, [:iso8601, 3], allow_nil: true
|
|
228
|
+
attribute :rating, format: {use: [:round, 1], allow_nil: true}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
A [`:default`](attributes.md#default) value is formatted too.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# Hash Records
|
|
2
|
+
|
|
3
|
+
The `:hash_access` attribute option reads values from Hash keys, for records
|
|
4
|
+
loaded as Hashes from JSON, Redis or raw SQL.
|
|
5
|
+
|
|
6
|
+
```ruby
|
|
7
|
+
class UserSerializer < Serega
|
|
8
|
+
attribute :name, hash_access: true # record[:name]
|
|
9
|
+
attribute :email, hash_access: :string # record["email"]
|
|
10
|
+
attribute :full_name, method: :name, hash_access: true # record[:name]
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
UserSerializer.to_h({:name => "Felonious", "email" => "gru@example.com"})
|
|
14
|
+
# => {name: "Felonious", email: "gru@example.com", full_name: "Felonious"}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Modes:
|
|
18
|
+
|
|
19
|
+
- `:symbol` reads `record[:name]`;
|
|
20
|
+
- `:string` reads `record["name"]`;
|
|
21
|
+
- `true` uses `config.hash_access.default_mode`, `:symbol` by default.
|
|
22
|
+
|
|
23
|
+
Records can be any objects with `#[]`, `#fetch` and `#key?`.
|
|
24
|
+
|
|
25
|
+
## Table of Contents
|
|
26
|
+
|
|
27
|
+
<!-- toc -->
|
|
28
|
+
|
|
29
|
+
- [Missing keys](#missing-keys)
|
|
30
|
+
- [Default access mode](#default-access-mode)
|
|
31
|
+
- [Delegating to nested Hashes](#delegating-to-nested-hashes)
|
|
32
|
+
- [Relations in Hashes](#relations-in-hashes)
|
|
33
|
+
|
|
34
|
+
<!-- tocstop -->
|
|
35
|
+
|
|
36
|
+
## Missing keys
|
|
37
|
+
|
|
38
|
+
A missing key raises `KeyError`. `allow_missing_key: true` serializes `nil`
|
|
39
|
+
instead:
|
|
40
|
+
|
|
41
|
+
```ruby
|
|
42
|
+
attribute :age, hash_access: true
|
|
43
|
+
# => KeyError: key not found: :age
|
|
44
|
+
|
|
45
|
+
attribute :age, hash_access: {allow_missing_key: true}
|
|
46
|
+
attribute :age, hash_access: {mode: :string, allow_missing_key: true}
|
|
47
|
+
# => {age: nil}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Default access mode
|
|
51
|
+
|
|
52
|
+
```ruby
|
|
53
|
+
class AppSerializer < Serega
|
|
54
|
+
config.hash_access.default_mode = :string # mode of `hash_access: true`
|
|
55
|
+
config.hash_access.default_allow_missing_key = true # nil for missing keys
|
|
56
|
+
end
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Delegating to nested Hashes
|
|
60
|
+
|
|
61
|
+
Delegates choose hash access per step: `:to_hash_access` reads the associated
|
|
62
|
+
record, `:hash_access` reads the final value. Both accept the same values as
|
|
63
|
+
the `:hash_access` attribute option.
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
attribute :city, delegate: {to: :address, to_hash_access: true} # record[:address].city
|
|
67
|
+
attribute :city, delegate: {to: :address, hash_access: true} # record.address[:city]
|
|
68
|
+
attribute :city, delegate: {to: :address, to_hash_access: true, hash_access: true} # record[:address][:city]
|
|
69
|
+
|
|
70
|
+
# record["address"][:city], nil when record has no "address"
|
|
71
|
+
attribute :city, delegate: {
|
|
72
|
+
to: :address,
|
|
73
|
+
allow_nil: true,
|
|
74
|
+
to_hash_access: {mode: :string, allow_missing_key: true},
|
|
75
|
+
hash_access: :symbol
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The `:hash_access` attribute option can not be combined with `:delegate`.
|
|
80
|
+
|
|
81
|
+
## Relations in Hashes
|
|
82
|
+
|
|
83
|
+
```ruby
|
|
84
|
+
class AddressSerializer < Serega
|
|
85
|
+
attribute :city, hash_access: true
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
class UserSerializer < Serega
|
|
89
|
+
attribute :address, hash_access: true, serializer: AddressSerializer
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
UserSerializer.to_h({address: {city: "Freedonia"}}) # => {address: {city: "Freedonia"}}
|
|
93
|
+
```
|