serega 0.51.1 → 0.52.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +49 -21
  3. data/VERSION +1 -1
  4. data/docs/README.md +42 -0
  5. data/docs/attributes.md +248 -0
  6. data/docs/batch-loading.md +207 -0
  7. data/docs/camel-case.md +86 -0
  8. data/docs/conditional-attributes.md +165 -0
  9. data/docs/configuration.md +47 -0
  10. data/docs/context.md +34 -0
  11. data/docs/errors.md +38 -0
  12. data/docs/formatters.md +262 -0
  13. data/docs/hash-records.md +93 -0
  14. data/docs/migrating-from-root-and-metadata.md +50 -0
  15. data/docs/preloads.md +125 -0
  16. data/docs/prepare-initial-objects.md +72 -0
  17. data/docs/presenter.md +87 -0
  18. data/docs/presets.md +174 -0
  19. data/docs/ractors.md +54 -0
  20. data/docs/relations.md +233 -0
  21. data/docs/responses-rails.md +287 -0
  22. data/docs/responses.md +293 -0
  23. data/docs/root-and-metadata.md +110 -0
  24. data/docs/selecting-fields.md +164 -0
  25. data/docs/serializing.md +113 -0
  26. data/docs/testing.md +230 -0
  27. data/lib/serega/attribute_normalizer.rb +26 -8
  28. data/lib/serega/attribute_normalizers/block.rb +3 -3
  29. data/lib/serega/config.rb +28 -13
  30. data/lib/serega/errors.rb +2 -2
  31. data/lib/serega/plan/cache.rb +13 -29
  32. data/lib/serega/plan/per_ractor_cache.rb +2 -2
  33. data/lib/serega/plan/point.rb +13 -2
  34. data/lib/serega/plan.rb +1 -1
  35. data/lib/serega/plugins/context_metadata/context_metadata.rb +5 -1
  36. data/lib/serega/plugins/metadata/metadata.rb +4 -0
  37. data/lib/serega/plugins/root/root.rb +14 -10
  38. data/lib/serega/plugins.rb +13 -0
  39. data/lib/serega/result_code/relation_point_code.rb +3 -2
  40. data/lib/serega/source_group.rb +1 -1
  41. data/lib/serega/validations/attribute/check_block.rb +4 -7
  42. data/lib/serega/validations/attribute/check_opt_hash_access.rb +2 -3
  43. data/lib/serega/validations/check_batch_loader_params.rb +2 -1
  44. data/lib/serega.rb +30 -26
  45. data/sig/serega.rbs +10 -8
  46. metadata +24 -1
@@ -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
@@ -0,0 +1,262 @@
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
+ A formatter also receives `nil`: `[:iso8601, 3]` on a missing time raises
27
+ `NoMethodError`. Add `allow_nil: true` to a formatter of a value that can be
28
+ `nil`, see [Formatting `nil` values](#formatting-nil-values).
29
+
30
+ ## Table of Contents
31
+
32
+ <!-- toc -->
33
+
34
+ - [Formatter kinds](#formatter-kinds)
35
+ - [Formatting `nil` values](#formatting-nil-values)
36
+ - [Formatters without a name](#formatters-without-a-name)
37
+ - [Common formatters](#common-formatters)
38
+ - [Times for JavaScript clients (`:iso8601`)](#times-for-javascript-clients-iso8601)
39
+ - [Dates (`:date`)](#dates-date)
40
+ - [Decimals as JSON numbers (`:float`)](#decimals-as-json-numbers-float)
41
+ - [Rounding (`:round2`)](#rounding-round2)
42
+ - [Percents (`:percent`)](#percents-percent)
43
+ - [Blank strings as `nil` (`:presence`)](#blank-strings-as-nil-presence)
44
+ - [API type names (`:type`)](#api-type-names-type)
45
+ - [Money (`:money`)](#money-money)
46
+ - [Decimals in JSON](#decimals-in-json)
47
+
48
+ <!-- tocstop -->
49
+
50
+ ## Formatter kinds
51
+
52
+ ```ruby
53
+ class AppSerializer < Serega
54
+ # A method name: value.to_s
55
+ formatter :string, :to_s
56
+
57
+ # A method name with arguments: value.iso8601(3)
58
+ formatter :iso8601, [:iso8601, 3]
59
+
60
+ # An operator is a method too: value * 100
61
+ formatter :percent, [:*, 100]
62
+
63
+ # A callable with the value
64
+ formatter :yes_no, ->(value) { value ? "yes" : "no" }
65
+
66
+ # A callable with the value and the context, as a second parameter or the :ctx keyword
67
+ formatter :money, ->(cents, ctx) { "#{cents / 100.0} #{ctx[:currency]}" }
68
+ formatter :price, ->(cents, ctx:) { "#{cents / 100.0} #{ctx[:currency]}" }
69
+
70
+ # A block
71
+ formatter(:upcase) { |value| value.upcase }
72
+ end
73
+ ```
74
+
75
+ A Symbol or an Array in a formatter is a plain Ruby method of the value, with
76
+ its arguments: `:to_s` calls `value.to_s`, and `[:iso8601, 3]` calls
77
+ `Time#iso8601(3)`. Serega adds no formatting methods of its own, so any method
78
+ of the value works, from Ruby, ActiveSupport or your own classes.
79
+
80
+ A method formatter is called directly in the generated serialization code,
81
+ which makes it the fastest kind.
82
+
83
+ ## Formatting `nil` values
84
+
85
+ A formatter formats `nil` too: a callable receives `nil`, and a method is
86
+ called on `nil`. With `allow_nil: true` a `nil` value stays `nil`.
87
+
88
+ ```ruby
89
+ formatter :iso8601, [:iso8601, 3], allow_nil: true
90
+ attribute :rating, format: {use: [:round, 1], allow_nil: true}
91
+ ```
92
+
93
+ A [`:default`](attributes.md#default) value is formatted too.
94
+
95
+ `:if_value` and `:unless_value` check the formatted value. Without
96
+ `allow_nil: true`, a formatter that turns `nil` into `0.0` keeps the
97
+ attribute that `unless_value: :nil?` should skip:
98
+
99
+ ```ruby
100
+ attribute :rating, format: ->(rating) { rating.to_f.round(1) }, unless_value: :nil?
101
+ # => {rating: 0.0} for a nil rating
102
+
103
+ attribute :rating, format: {use: ->(rating) { rating.to_f.round(1) }, allow_nil: true}, unless_value: :nil?
104
+ # => {} for a nil rating
105
+ ```
106
+
107
+ ## Formatters without a name
108
+
109
+ `:format` also accepts a formatter directly. A Symbol is always a formatter
110
+ name, so a method name alone needs a named formatter.
111
+
112
+ ```ruby
113
+ attribute :rating, format: [:round, 1]
114
+ attribute :email, format: ->(email) { email.downcase }
115
+ attribute :nickname, format: {use: :upcase, allow_nil: true}
116
+ ```
117
+
118
+ `allow_nil:` needs the Hash form, with the formatter under `:use`.
119
+
120
+ ## Common formatters
121
+
122
+ Examples of formatters that many APIs use. Copy the ones you need, for
123
+ example into a base serializer, and change them as you like. The names, such
124
+ as `:round2`, are yours to choose. The methods they call are Ruby's:
125
+ `Time#iso8601`, `Date#iso8601`, `BigDecimal#to_f`, `Float#round` and
126
+ ActiveSupport's `Object#presence`.
127
+
128
+ ### Times for JavaScript clients (`:iso8601`)
129
+
130
+ JavaScript dates resolve to milliseconds, so three fraction digits are enough.
131
+
132
+ ```ruby
133
+ formatter :iso8601, [:iso8601, 3], allow_nil: true
134
+
135
+ attribute :created_at, format: :iso8601
136
+ # Time.utc(2026, 11, 16, 10, 30, 15.123456) => "2026-11-16T10:30:15.123Z"
137
+ # nil => nil
138
+ ```
139
+
140
+ ### Dates (`:date`)
141
+
142
+ ```ruby
143
+ formatter :date, :iso8601, allow_nil: true
144
+
145
+ attribute :birthday, format: :date
146
+ # Date.new(2026, 11, 16) => "2026-11-16"
147
+ ```
148
+
149
+ ### Decimals as JSON numbers (`:float`)
150
+
151
+ Decimal columns return a `BigDecimal`, which JSON writes as a String, see
152
+ [Decimals in JSON](#decimals-in-json).
153
+
154
+ ```ruby
155
+ formatter :float, :to_f, allow_nil: true
156
+
157
+ attribute :latitude, format: :float
158
+ # BigDecimal("51.501364") => 51.501364
159
+ # nil => nil
160
+ ```
161
+
162
+ ### Rounding (`:round2`)
163
+
164
+ ```ruby
165
+ formatter :round2, [:round, 2]
166
+
167
+ attribute :ratio, format: :round2
168
+ # 12.345 => 12.35
169
+ ```
170
+
171
+ ### Percents (`:percent`)
172
+
173
+ ```ruby
174
+ formatter :percent, ->(fraction) { (fraction * 100).round(2) }
175
+
176
+ attribute :conversion, format: :percent
177
+ # 0.125 => 12.5
178
+ ```
179
+
180
+ ### Blank strings as `nil` (`:presence`)
181
+
182
+ `Object#presence` comes from ActiveSupport.
183
+
184
+ ```ruby
185
+ formatter :presence, :presence
186
+
187
+ attribute :bio, format: :presence
188
+ # "" => nil
189
+ # "Freedonia" => "Freedonia"
190
+ ```
191
+
192
+ ### API type names (`:type`)
193
+
194
+ Clients that store records by type and id need a type in every record. A
195
+ constant attribute holds the model, and the formatter names its type. The
196
+ formatter takes a class or a class name, so it also names the type of a
197
+ polymorphic `*_type` column.
198
+
199
+ ```ruby
200
+ TYPES = {"User" => "users", "Post" => "posts"}.freeze
201
+ formatter :type, ->(model) { TYPES.fetch(model.to_s) }
202
+
203
+ attribute :type, const: User, format: :type
204
+ # User => "users"
205
+
206
+ attribute :commentable_type, format: :type
207
+ # "Post" => "posts"
208
+ ```
209
+
210
+ `TYPES.fetch` raises `KeyError` for a model without a type, so a new model
211
+ can't send a wrong one. The Hash keeps API type names apart from class names:
212
+ renaming a model doesn't change the API, and `TYPES.invert` turns a type from
213
+ a request back into a class name.
214
+
215
+ ### Money (`:money`)
216
+
217
+ Money in cents, without trailing zeros. A formatter that depends on the
218
+ locale or the currency fits a callable class:
219
+ `formatter :money, MoneyFormatter.new`.
220
+
221
+ ```ruby
222
+ formatter :money, ->(cents) { format("$%.2f", cents / 100.0).delete_suffix(".00") }
223
+
224
+ attribute :price_cents, format: :money
225
+ # 1999 => "$19.99"
226
+ # 2000 => "$20"
227
+ ```
228
+
229
+ ## Decimals in JSON
230
+
231
+ Serega returns a `BigDecimal` as is, and `to_json` writes it with
232
+ `JSON.generate`. Without ActiveSupport this writes it as a String in
233
+ scientific notation: `"0.51501364e2"`. With ActiveSupport, as in Rails, it
234
+ writes `"51.501364"`. A formatter gives the same output in both cases.
235
+
236
+ ```ruby
237
+ class PlaceSerializer < Serega
238
+ attribute :latitude
239
+ attribute :longitude
240
+ end
241
+
242
+ PlaceSerializer.to_json(place)
243
+ # => "{\"latitude\":\"0.51501364e2\",\"longitude\":\"-0.14189e0\"}" without ActiveSupport
244
+ # => "{\"latitude\":\"51.501364\",\"longitude\":\"-0.14189\"}" with ActiveSupport
245
+ ```
246
+
247
+ With a formatter, the decimals are JSON numbers:
248
+
249
+ ```ruby
250
+ class PlaceSerializer < Serega
251
+ # JSON numbers: value.to_f
252
+ attribute :latitude, format: [:to_f]
253
+ attribute :longitude, format: [:to_f]
254
+ end
255
+
256
+ PlaceSerializer.to_json(place)
257
+ # => "{\"latitude\":51.501364,\"longitude\":-0.14189}"
258
+ ```
259
+
260
+ A Float keeps about 17 significant digits, thus `to_f` rounds longer decimals:
261
+ `BigDecimal("12345678901234567.89").to_f` is `1.2345678901234568e+16`. For a
262
+ String with every digit, use `format: [:to_s, "F"]`.