field_struct 0.15.0 → 1.0.0.pre1
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/.claude-plugin/marketplace.json +13 -0
- data/.claude-plugin/plugin.json +9 -0
- data/AGENTS.md +47 -54
- data/CHANGELOG.md +53 -640
- data/LICENSE.txt +21 -0
- data/README.md +33 -628
- data/USAGE.md +771 -715
- data/docs/getting_started.md +139 -325
- data/lib/field_struct/base.rb +241 -1149
- data/lib/field_struct/class_macros.rb +163 -0
- data/lib/field_struct/describer.rb +167 -0
- data/lib/field_struct/errors.rb +182 -62
- data/lib/field_struct/exceptions.rb +40 -0
- data/lib/field_struct/field.rb +69 -135
- data/lib/field_struct/field_builder.rb +110 -0
- data/lib/field_struct/field_checks.rb +50 -0
- data/lib/field_struct/introspection.rb +199 -0
- data/lib/field_struct/json_codec.rb +240 -0
- data/lib/field_struct/metadata.rb +65 -260
- data/lib/field_struct/model_name.rb +27 -27
- data/lib/field_struct/option_checker.rb +121 -0
- data/lib/field_struct/partial.rb +49 -0
- data/lib/field_struct/presence.rb +45 -0
- data/lib/field_struct/rbs.rb +151 -271
- data/lib/field_struct/registered_option.rb +113 -0
- data/lib/field_struct/registry.rb +40 -50
- data/lib/field_struct/restrictions.rb +90 -0
- data/lib/field_struct/scaffold.rb +274 -301
- data/lib/field_struct/suggestion.rb +33 -0
- data/lib/field_struct/types/array.rb +147 -126
- data/lib/field_struct/types/base.rb +113 -124
- data/lib/field_struct/types/big_decimal.rb +59 -55
- data/lib/field_struct/types/binary.rb +18 -25
- data/lib/field_struct/types/boolean.rb +74 -97
- data/lib/field_struct/types/builtin.rb +32 -0
- data/lib/field_struct/types/date.rb +23 -137
- data/lib/field_struct/types/datetime.rb +30 -139
- data/lib/field_struct/types/element_options.rb +51 -0
- data/lib/field_struct/types/email.rb +27 -38
- data/lib/field_struct/types/float.rb +58 -56
- data/lib/field_struct/types/format_presets.rb +30 -0
- data/lib/field_struct/types/hash.rb +144 -0
- data/lib/field_struct/types/immutable_string.rb +16 -9
- data/lib/field_struct/types/integer.rb +74 -102
- data/lib/field_struct/types/nested.rb +57 -58
- data/lib/field_struct/types/preset_resolver.rb +9 -24
- data/lib/field_struct/types/rfc3339_format.rb +70 -153
- data/lib/field_struct/types/string.rb +48 -46
- data/lib/field_struct/types/symbol.rb +23 -20
- data/lib/field_struct/types/temporal.rb +232 -0
- data/lib/field_struct/types/time.rb +32 -145
- data/lib/field_struct/types/union.rb +111 -65
- data/lib/field_struct/types/union_pick.rb +139 -0
- data/lib/field_struct/types/url.rb +24 -35
- data/lib/field_struct/types/uuid.rb +24 -35
- data/lib/field_struct/types/value.rb +14 -9
- data/lib/field_struct/types/zone.rb +118 -0
- data/lib/field_struct/version.rb +3 -3
- data/lib/field_struct.rb +102 -122
- data/sig/field_struct.rbs +1180 -2300
- data/sig/manifest.yaml +6 -0
- data/skills/field-struct/SKILL.md +73 -159
- metadata +37 -28
- data/CODE_OF_CONDUCT.md +0 -132
- data/UPGRADING.md +0 -743
- data/lib/field_struct/error.rb +0 -48
- data/lib/field_struct/types/temporal_parser.rb +0 -93
- data/lib/field_struct/types/time_format_resolver.rb +0 -54
- data/lib/field_struct/types/zone_option.rb +0 -267
data/USAGE.md
CHANGED
|
@@ -1,820 +1,876 @@
|
|
|
1
|
-
#
|
|
1
|
+
# field_struct usage reference
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
agent (or human) to load once and use the whole API correctly. For narrative
|
|
5
|
-
docs see `README.md`; for design rationale see `docs/origin/plan.md`.
|
|
3
|
+
A dense, example-first reference. Read it once; every example runs.
|
|
6
4
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
- [Declaring](#declaring) · [Reading and writing](#reading-and-writing) · [Errors](#errors) · [Types](#types)
|
|
6
|
+
- [Arrays, maps, nested structs, unions](#arrays-maps-nested-structs-unions) · [Dates, times, zones](#dates-times-zones)
|
|
7
|
+
- [Class settings](#class-settings) · [Validation](#validation) · [JSON](#json) · [Introspection](#introspection)
|
|
8
|
+
- [Type signatures](#type-signatures) · [Custom types](#custom-types) · [Exceptions](#exceptions)
|
|
10
9
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
10
|
+
## Declaring
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
required :name, :type, **options # must be present
|
|
14
|
+
optional :name, :type, **options # may be missing
|
|
15
|
+
field :name, :type, **options # optional unless required: true
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`name` is a Symbol or String. `type` is a registered name (`:string`), a `FieldStruct::Base` subclass, or a type class.
|
|
19
|
+
Declaring a name twice replaces the first. Reserved names (`errors`, `attributes`, `to_h`, `hash`, `class`, ...) raise
|
|
20
|
+
`ArgumentError` at declaration. Every declaration problem raises while the class body runs, never at first use.
|
|
21
|
+
|
|
22
|
+
```ruby run
|
|
23
|
+
require 'field_struct'
|
|
24
|
+
|
|
25
|
+
class Specimen < FieldStruct::Base
|
|
26
|
+
required :name, :string, description: 'Display label'
|
|
27
|
+
optional :height, :integer, in: 0..150
|
|
28
|
+
optional :role, :symbol, enum: %i[wild bred], default: :bred
|
|
29
|
+
field :email, :email, required: true
|
|
30
|
+
optional :seen, :time, default: -> { Time.at(0).utc } # a callable default runs per instance
|
|
31
|
+
optional :token, :string, sensitive: true
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
specimen = Specimen.new(name: 'Ivy', email: 'curator@example.org')
|
|
35
|
+
specimen.role # => :bred
|
|
36
|
+
specimen.height # => nil
|
|
37
|
+
specimen.valid? # => true
|
|
38
|
+
Specimen.attribute_names # => [:name, :height, :role, :email, :seen, :token]
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Options valid on every type
|
|
42
|
+
|
|
43
|
+
| Option | Values | Notes |
|
|
44
|
+
|---|---|---|
|
|
45
|
+
| `required:` | `true` / `false` | `required` and `optional` force it |
|
|
46
|
+
| `default:` | literal or callable | `nil` means no default. A callable (anything that responds to `call`) runs once per instance |
|
|
47
|
+
| `coercion_policy:` | `:keep_raw` `:replace` `:raise` | overrides the class policy for this field |
|
|
48
|
+
| `description:` / `desc:` | String | passing both raises |
|
|
49
|
+
| `rbs_type:` | non-blank String | replaces the derived RBS type |
|
|
50
|
+
| `sensitive:` | `true` / `false` only | masks the value in `inspect` as `[FILTERED]` |
|
|
51
|
+
|
|
52
|
+
A key that some *other* type declares raises at declaration (`round:` on a string field: `round: option does not apply
|
|
53
|
+
to String fields. It applies to: Float, BigDecimal.`). A key nobody declares raises too, with a suggestion when one is
|
|
54
|
+
close, so a typo like `requird: true` fails at load instead of doing nothing:
|
|
55
|
+
|
|
56
|
+
```ruby run
|
|
57
|
+
class Ledger < FieldStruct::Base
|
|
58
|
+
required :folio, :integer
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
begin
|
|
62
|
+
Ledger.optional :spine, :string, requird: true
|
|
63
|
+
rescue ArgumentError => e
|
|
64
|
+
e.message # => "unknown option requird: on Ledger#spine (did you mean required:?)"
|
|
65
|
+
end
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
An exporter or app that reads its own key registers it first with `FieldStruct.register_option(name, type:, owner:)`.
|
|
69
|
+
After that the key is accepted on any field, its value is checked against `type:` (`nil` is always fine), and it's
|
|
70
|
+
stored in `field.options` untouched. It does nothing at runtime. The adapters register theirs when you require them
|
|
71
|
+
(`avro:`, `proto:`, `json_schema:`), and using one before its adapter loads says which file to require.
|
|
72
|
+
|
|
73
|
+
```ruby run
|
|
74
|
+
FieldStruct.register_option(:catalog, type: Hash, owner: 'ledger_app') # => :catalog
|
|
75
|
+
|
|
76
|
+
class Ledger
|
|
77
|
+
optional :clasp, :string, catalog: {shelf: 'B4'}
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
Ledger.metadata[:clasp].options # => {catalog: {shelf: "B4"}}
|
|
81
|
+
FieldStruct.registered_options[:catalog].owner # => "ledger_app"
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Registering the same name, type and owner again does nothing; anything else that already has the name, a universal
|
|
85
|
+
option or a built-in type's option raises. `FieldStruct.registered_options` lists every registration in order, each a
|
|
86
|
+
`FieldStruct::RegisteredOption` with `name`, `type` (an Array of classes) and `owner`.
|
|
87
|
+
|
|
88
|
+
## Reading and writing
|
|
89
|
+
|
|
90
|
+
```ruby run
|
|
91
|
+
require 'field_struct'
|
|
92
|
+
|
|
93
|
+
class Quadrat < FieldStruct::Base
|
|
94
|
+
required :row, :integer
|
|
95
|
+
required :col, :integer
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
quadrat = Quadrat.new('row' => '3', col: 4.9) # String or Symbol keys; values are coerced
|
|
99
|
+
quadrat.row # => 3
|
|
100
|
+
quadrat.col # => 4
|
|
101
|
+
quadrat.attributes # => {row: 3, col: 4}
|
|
102
|
+
quadrat.to_h == quadrat.attributes # => true
|
|
103
|
+
quadrat.row = '10' # writers coerce too
|
|
104
|
+
quadrat.row # => 10
|
|
105
|
+
quadrat.assign_attributes(row: 1, col: 2) # bulk, same pipeline
|
|
106
|
+
quadrat.with(col: 9).col # => 9
|
|
107
|
+
quadrat.col # => 2
|
|
108
|
+
quadrat == Quadrat.new(row: 1, col: 2) # => true
|
|
109
|
+
quadrat.invalid? # => false
|
|
110
|
+
quadrat.deconstruct_keys([:row]) # => {row: 1}
|
|
111
|
+
quadrat.deconstruct # => [1, 2]
|
|
112
|
+
Quadrat.new(nil).attributes # => {row: nil, col: nil}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`new` takes a Hash, or anything that responds to `to_hash`. Anything else raises
|
|
116
|
+
`ArgumentError: Quadrat.new expects a Hash (or an object responding to #to_hash), got Array`.
|
|
117
|
+
Pattern matching works: `case quadrat in {row:, col:} ...`.
|
|
118
|
+
|
|
119
|
+
`given_fields` lists the fields the caller gave, in declaration order, so "sent as null" and "not sent" stay apart
|
|
120
|
+
(what a PATCH body needs). Defaults and unknown keys never count:
|
|
121
|
+
|
|
122
|
+
```ruby run
|
|
123
|
+
class Transect < FieldStruct::Base
|
|
124
|
+
required :site, :string
|
|
125
|
+
optional :bearing, :integer, default: 0
|
|
126
|
+
optional :remark, :string
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
walk = Transect.new(site: 'ridge', remark: nil)
|
|
130
|
+
walk.given_fields # => [:site, :remark]
|
|
131
|
+
walk.with(bearing: 90).given_fields # => [:site, :bearing, :remark]
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Errors
|
|
135
|
+
|
|
136
|
+
`obj.errors` is a `FieldStruct::Errors`. It records, it never raises.
|
|
137
|
+
|
|
138
|
+
| Message | When |
|
|
139
|
+
|---|---|
|
|
140
|
+
| `"is required"` | a required field is missing (nil, blank string, empty array) |
|
|
141
|
+
| `"is invalid"` | `format:`, `enum:` or `in:` failed, or a nested struct inside is invalid |
|
|
142
|
+
| `"could not be coerced: <reason>"` | the type could not read the value |
|
|
143
|
+
| anything you add | from `validate` |
|
|
144
|
+
|
|
145
|
+
```ruby run
|
|
146
|
+
require 'field_struct'
|
|
147
|
+
|
|
148
|
+
class Seedling < FieldStruct::Base
|
|
149
|
+
required :batch, :string, format: /\A[A-Z]{3}-\d+\z/
|
|
150
|
+
optional :trays, :integer
|
|
16
151
|
end
|
|
17
152
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
153
|
+
tray = Seedling.new(batch: 'abc', trays: 'lots')
|
|
154
|
+
tray.valid? # => false
|
|
155
|
+
tray.errors[:batch] # => ["is invalid"]
|
|
156
|
+
tray.errors[:trays].first.start_with?('could not be coerced') # => true
|
|
157
|
+
tray.errors.full_messages.first # => "Batch is invalid"
|
|
158
|
+
tray.errors.empty? # => false
|
|
159
|
+
tray.errors.add(:base, 'Something else')
|
|
160
|
+
tray.errors.full_messages.last # => "Something else"
|
|
161
|
+
tray.errors.clear(:batch)
|
|
162
|
+
tray.errors[:batch] # => []
|
|
163
|
+
tray.batch = 'ABC-1' # assigning re-checks the field
|
|
164
|
+
tray.errors[:batch] # => []
|
|
165
|
+
tray.errors.messages.keys # => [:trays, :base]
|
|
23
166
|
```
|
|
24
167
|
|
|
25
|
-
|
|
168
|
+
`errors.messages` is a Hash of field to messages. `errors.paths` keys the same messages by where they happened, so a
|
|
169
|
+
nested struct's message lands on its own field instead of the parent's `"is invalid"`:
|
|
170
|
+
|
|
171
|
+
```ruby run
|
|
172
|
+
require 'field_struct'
|
|
173
|
+
|
|
174
|
+
class Bed < FieldStruct::Base
|
|
175
|
+
required :rows, :integer
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
class Plot < FieldStruct::Base
|
|
179
|
+
required :label, :string
|
|
180
|
+
optional :bed, Bed
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
plot = Plot.new(label: 'north', bed: { rows: nil })
|
|
184
|
+
plot.errors[:bed] # => ["is invalid"]
|
|
185
|
+
plot.errors.paths # => {"bed.rows" => ["is required"]}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
`errors.freeze` freezes the messages too, so `add` and `clear` raise `FrozenError`, and `valid?` then reads them as
|
|
189
|
+
they are instead of running the validators. A `dup` gets errors it can change again.
|
|
190
|
+
|
|
191
|
+
Messages never contain the offending value, only its class. Errors are per assignment: assigning again clears the
|
|
192
|
+
field's old messages and runs the checks again. `batch: nil` on a required field gives `"is required"`; the value is nil.
|
|
193
|
+
|
|
194
|
+
### What a failed coercion does (`coercion_policy`)
|
|
195
|
+
|
|
196
|
+
| Policy | Behaviour |
|
|
197
|
+
|---|---|
|
|
198
|
+
| `:keep_raw` (default) | the raw input is stored, one `could not be coerced` message is recorded |
|
|
199
|
+
| `:replace` | the field becomes `nil`, the message is recorded |
|
|
200
|
+
| `:raise` | `FieldStruct::CoercionError` (with `field_name` and `original`) |
|
|
201
|
+
|
|
202
|
+
```ruby run
|
|
203
|
+
require 'field_struct'
|
|
204
|
+
|
|
205
|
+
class Forgiving < FieldStruct::Base
|
|
206
|
+
optional :a, :integer
|
|
207
|
+
optional :b, :integer, coercion_policy: :replace
|
|
208
|
+
optional :c, :integer, coercion_policy: :raise
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
l = Forgiving.new(a: 'x', b: 'y')
|
|
212
|
+
l.a # => "x"
|
|
213
|
+
l.b # => nil
|
|
214
|
+
begin
|
|
215
|
+
Forgiving.new(c: 'z')
|
|
216
|
+
rescue FieldStruct::CoercionError => e
|
|
217
|
+
e.field_name # => :c
|
|
218
|
+
end
|
|
219
|
+
```
|
|
26
220
|
|
|
27
221
|
## Types
|
|
28
222
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
|
37
|
-
|
|
|
38
|
-
|
|
|
39
|
-
|
|
|
40
|
-
|
|
|
41
|
-
|
|
|
42
|
-
|
|
|
43
|
-
|
|
|
44
|
-
|
|
|
45
|
-
|
|
|
46
|
-
|
|
|
47
|
-
|
|
|
48
|
-
|
|
|
49
|
-
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
## Field options (any type)
|
|
81
|
-
|
|
82
|
-
| Option | Meaning |
|
|
83
|
-
|--------|---------|
|
|
84
|
-
| `required: true` | presence-checked (`required :x` is sugar; `optional :x` / bare `field :x` are not) |
|
|
85
|
-
| `default:` | literal, **or** a callable (`-> { Time.now }`, a Proc/Method) invoked once per instance |
|
|
86
|
-
| `coercion_policy:` | `:keep_raw` (default) \| `:replace` \| `:raise` — per-field override of the class setting |
|
|
87
|
-
| `description:` / `desc:` | human text; introspection only — **never** in `attributes`/`as_json`/pattern match |
|
|
88
|
-
| `rbs_type:` | String of RBS that `FieldStruct::RBS` emits for this field instead of the derived type (`'::ActiveRecord::Relation'`); signatures only, no runtime effect |
|
|
89
|
-
| `sensitive:` | `true` renders `[FILTERED]` for the value in `inspect` / `pp`; data paths unchanged — see [Log safety](#log-safety-error-messages-and-sensitive-fields) |
|
|
90
|
-
|
|
91
|
-
```ruby
|
|
92
|
-
class Account < FieldStruct::Base
|
|
93
|
-
required :id, :uuid, default: -> { SecureRandom.uuid }, desc: 'primary key'
|
|
94
|
-
optional :balance, :big_decimal, default: 0, coercion_policy: :raise
|
|
95
|
-
end
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
Type-specific options: `format:` (string-shaped + date/time/datetime — a regex or a
|
|
99
|
-
strftime string or a preset Symbol), `round:` (float/decimal — Integer places),
|
|
100
|
-
`base:` (integer — radix 2..36 for string input, default 10), `strict:` (string-shaped
|
|
101
|
-
and integer — Boolean; see [Strict coercion](#strict-coercion-strict-true)),
|
|
102
|
-
`values:` (boolean — a `{truthy:, falsy:}` Hash or a preset Symbol), `of:` (array
|
|
103
|
-
element type / union member array), `element:` (array — a Hash of the element
|
|
104
|
-
type's own options; see [Element options](#element-options-element)), `enum:` (string-like — Array of allowed values),
|
|
105
|
-
`in:` (numeric/temporal — Array or Range), `zone:` (time/datetime — `"UTC"`,
|
|
106
|
-
`"±HH:MM"` or an IANA name like `"America/Denver"` for zone-less input; see [Zones](#zones-zone)).
|
|
107
|
-
|
|
108
|
-
```ruby
|
|
109
|
-
required :joined, :date, format: '%m/%d/%Y' # custom strftime
|
|
110
|
-
required :paid, :boolean, values: :english_yes_no
|
|
111
|
-
required :flag, :boolean, values: { truthy: %w[on], falsy: %w[off] }
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
Boolean presets: `:english_yes_no`/`:english` (`true yes y on 1` / `false no n off 0`),
|
|
115
|
-
`:numeric` (`1`/`0`). Date presets: `:iso8601 :us :eu`. Time/DateTime presets:
|
|
116
|
-
`:iso8601 :rfc2822 :db`.
|
|
117
|
-
|
|
118
|
-
### The numeric contract
|
|
119
|
-
|
|
120
|
-
- **Integer strings are base 10.** `"010"` is 10 and `"007"` is 7 — not octal —
|
|
121
|
-
and `"0x1A"` / `"0b11"` are refused rather than read as hex/binary. Surrounding
|
|
122
|
-
whitespace and digit underscores are fine (`" 42 "` → 42, `"1_000"` → 1000).
|
|
123
|
-
Declare `base:` (2..36, checked at class load) for another radix:
|
|
124
|
-
`field :code, :integer, base: 16` reads `"1A"` as 26. Integers pass through and
|
|
125
|
-
Floats still truncate; `base:` only affects strings.
|
|
126
|
-
- **Float strings are base 10 too.** `"0x1A"` (which `Kernel.Float` reads as 26.0)
|
|
127
|
-
is refused, like `"0b101"` and `"0o17"`. Every other `Kernel.Float` form still
|
|
128
|
-
reads: `"1_000.5"`, `" 2.5 "`, `"1e3"`, `".5"`, `"017"` (→ 17.0).
|
|
129
|
-
- **NaN and ±Infinity are never valid.** `:integer`, `:float` and `:decimal` refuse
|
|
130
|
-
them — as a Float, a BigDecimal, a String (`"NaN"`, `"Infinity"`) or JSON `1e400` —
|
|
131
|
-
as an ordinary coercion failure under the field's `coercion_policy`. A `:union`
|
|
132
|
-
refuses a non-finite Float/BigDecimal outright rather than letting a `:string`
|
|
133
|
-
member store `"NaN"`. Like every FieldStruct message, these name the input class,
|
|
134
|
-
never the value — see [Log safety](#log-safety-error-messages-and-sensitive-fields).
|
|
135
|
-
- **`round:` keeps the field's type and rounds half up** (ties away from zero).
|
|
136
|
-
`round: 0` returns a `Float` / `BigDecimal`, not an Integer, and `:decimal`
|
|
137
|
-
ignores the process-global `BigDecimal.mode` — a host that sets banker's rounding
|
|
138
|
-
still gets `12.345` → `12.35` at `round: 2`.
|
|
139
|
-
|
|
140
|
-
### Strict coercion (`strict: true`)
|
|
141
|
-
|
|
142
|
-
The defaults are lenient on purpose — they match what ActiveModel does, so a Rails
|
|
143
|
-
client sees the same values. A field that must not accept "close enough" (amounts,
|
|
144
|
-
account numbers) can opt in per field with `strict: true`. Strict only *narrows*:
|
|
145
|
-
anything it accepts becomes exactly what the default would make of it.
|
|
146
|
-
|
|
147
|
-
| Input | `:string` | `:string, strict: true` | `:integer` | `:integer, strict: true` |
|
|
148
|
-
|-------|-----------|-------------------------|------------|--------------------------|
|
|
149
|
-
| `"abc"` / `"42"` | `"abc"` / `"42"` | same | — / 42 | — / 42 |
|
|
150
|
-
| `:abc` | `"abc"` | `"abc"` | `TypeError` | `TypeError` |
|
|
151
|
-
| `42` | `"42"` | `"42"` | 42 | 42 |
|
|
152
|
-
| `12.0` / `BigDecimal("12.0")` | `"12.0"` / `"0.12e2"` | `TypeError` | 12 / 12 | 12 / 12 |
|
|
153
|
-
| `12.7` / `Rational(25, 2)` | `"12.7"` / `"25/2"` | `TypeError` | 12 (truncated) | `ArgumentError` |
|
|
154
|
-
| `"12.7"` / `"12.0"` / `"1e3"` / `"0x1A"` | as-is | as-is | `ArgumentError` | `ArgumentError` |
|
|
155
|
-
| object with `to_str` | `to_s` | `to_s` | read as its `to_str` string | read as its `to_str` string |
|
|
156
|
-
| `{a: 1}` / `[1]` / `true` / `Time` / `Object.new` | their `to_s` | `TypeError` | `TypeError` (a `Time` reads as its epoch) | `TypeError` (a `Time` → `ArgumentError`) |
|
|
157
|
-
| `Float::NAN` / `Infinity` | `"NaN"` / `"Infinity"` | `TypeError` | `ArgumentError` | `ArgumentError` |
|
|
158
|
-
|
|
159
|
-
- **`:string` strict** accepts a String, a Symbol, an Integer and anything
|
|
160
|
-
responding to `to_str`. An Integer counts because a JSON payload often carries an
|
|
161
|
-
identifier as a number (`"account": 12345`) and its text is unambiguous. A Float,
|
|
162
|
-
BigDecimal or Rational is refused: its `to_s` (`"1.0e+20"`, `"0.12e2"`, `"1/2"`)
|
|
163
|
-
is not the text the sender meant. Booleans, Hashes,
|
|
164
|
-
Arrays, Complex and other objects are refused — their `to_s` is a rendering, not
|
|
165
|
-
a value. It applies to the string subtypes too (`:immutable_string`, `:uuid`,
|
|
166
|
-
`:url`, `:email`, `:binary`).
|
|
167
|
-
- **`:integer` strict** accepts a value only when it *is* a whole number: an
|
|
168
|
-
Integer, or a numeric equal to its integer (`12.0`, `BigDecimal("12")`,
|
|
169
|
-
`Rational(24, 2)`). Strings follow the default rules exactly — integer digits in
|
|
170
|
-
base 10 or `base:` — so a float-shaped string like `"12.0"` or `"1e3"` is refused
|
|
171
|
-
in both modes.
|
|
172
|
-
- Refusals are ordinary coercion failures under the field's `coercion_policy`, and
|
|
173
|
-
their messages name the input class, never the value.
|
|
174
|
-
- `strict:` must be `true`/`false` (checked at declaration); on any other type it
|
|
175
|
-
raises `strict: option does not apply to Float fields. It applies to: String, ImmutableString, Integer, …`
|
|
176
|
-
|
|
177
|
-
<!-- doctest -->
|
|
178
|
-
```ruby
|
|
179
|
-
class Charge < FieldStruct::Base
|
|
180
|
-
required :reference, :string, strict: true
|
|
181
|
-
required :cents, :integer, strict: true
|
|
182
|
-
end
|
|
183
|
-
|
|
184
|
-
Charge.new(reference: :ord_1, cents: 1250.0).cents # => 1250
|
|
185
|
-
Charge.new(reference: { id: 1 }, cents: 1).valid? # => false
|
|
186
|
-
Charge.new(reference: 'ord_1', cents: 12.5).valid? # => false
|
|
187
|
-
```
|
|
188
|
-
|
|
189
|
-
### The temporal contract
|
|
190
|
-
|
|
191
|
-
Three rules apply to `:date` / `:time` / `:datetime`, and they exist because the
|
|
192
|
-
stdlib parsers answer questions they were not asked.
|
|
193
|
-
|
|
194
|
-
- **A declared `format:` anchors.** `'2026-07-031'` under `'%Y-%m-%d'` is refused
|
|
195
|
-
rather than read as the 3rd with the trailing character dropped. "Anchor" means
|
|
196
|
-
trailing-junk rejection and nothing more — a hand-written format stays
|
|
197
|
-
strptime-lenient about widths and sign, because `%m` accepting one or two digits
|
|
198
|
-
is strptime's contract.
|
|
199
|
-
- **A day that never existed is refused**, by all three types. `'2026-06-31'` is
|
|
200
|
-
not 1 July.
|
|
201
|
-
- **With no declared format, the string must name a whole day.** `Time.parse('10:30')`
|
|
202
|
-
is *today* at 10:30 and `'July'` is 1 July of this year; a value whose meaning
|
|
203
|
-
depends on when it was parsed is not a value. A *declared* partial format
|
|
204
|
-
(`format: '%H:%M'`) is a deliberate choice and still works.
|
|
205
|
-
|
|
206
|
-
A blank string is a coercion failure, as it already was for `:integer`, `:float`,
|
|
207
|
-
`:big_decimal` and `:boolean`. Only `:string` treats blank as missing.
|
|
208
|
-
|
|
209
|
-
**`format: :iso8601` is RFC 3339**, which is what "ISO-8601" means in an API
|
|
210
|
-
contract and what JSON Schema's `date-time` refers to. FieldStruct parses and
|
|
211
|
-
renders it itself rather than delegating to `Time.iso8601` / `DateTime.iso8601`,
|
|
212
|
-
which disagree with each other (and `Time.iso8601` reads `2026-02-30T10:30:00Z`
|
|
213
|
-
as 2 March). It accepts full-width fields, a `T` separator, whole seconds,
|
|
214
|
-
optional fractional seconds, and a **mandatory** offset (`Z` or `±hh:mm`); it
|
|
215
|
-
refuses `2026-7-3`, `+2026-07-03`, `20261-07-03`, `20260703`, week and ordinal
|
|
216
|
-
dates, a missing offset, hour 24 and second 60. Output is `Z` for UTC and
|
|
217
|
-
`+HH:MM` otherwise.
|
|
218
|
-
|
|
219
|
-
```ruby
|
|
220
|
-
required :on, :date, format: :iso8601 # 2026-07-03 exactly, and a real day
|
|
221
|
-
required :at, :datetime, format: :iso8601 # 2026-07-03T10:30:00Z, offset required
|
|
222
|
-
```
|
|
223
|
-
|
|
224
|
-
That strictness is the point: it is what lets you declare the field instead of
|
|
225
|
-
hand-rolling `format: /\A\d{4}-\d{2}-\d{2}\z/` plus a validator. The other
|
|
226
|
-
presets (`:us`, `:eu`, `:db`, `:rfc2822`) are display and interchange formats, so
|
|
227
|
-
they stay strftime-based — with anchoring and civil-date validity still applied.
|
|
228
|
-
|
|
229
|
-
### Zones (`zone:`)
|
|
230
|
-
|
|
231
|
-
By default a zone-less string follows the stdlib semantics of the type you
|
|
232
|
-
declared: `:time` uses `Time.parse` and lands in the *process* zone, `:datetime`
|
|
233
|
-
uses `DateTime.parse` and lands in **UTC**. So `"2026-10-22 10:00"` in a `:time`
|
|
234
|
-
field is a different instant on a server in Denver than on one in Tokyo.
|
|
235
|
-
|
|
236
|
-
Declare `zone:` on a `:time` or `:datetime` field to name the zone a zone-less
|
|
237
|
-
value means. The same input then gives the same answer on any server. `zone:`
|
|
238
|
-
only fills in a **missing** offset — it never changes one the input carries.
|
|
239
|
-
|
|
240
|
-
`zone:` takes `"UTC"`, a fixed offset (`"-06:00"`, the same all year) or an IANA
|
|
241
|
-
name (`"America/Denver"`, which follows daylight saving: -06:00 in July, -07:00 in
|
|
242
|
-
January). With a name, a wall-clock time gets the offset in force **at that date**.
|
|
243
|
-
|
|
244
|
-
| Input | no `zone:` | `zone: "-06:00"` | `zone: "America/Denver"` |
|
|
245
|
-
|-------|------------|------------------|--------------------------|
|
|
246
|
-
| `"2026-10-22 10:00"` (no offset) | `:time` process zone; `:datetime` UTC | 10:00 at -06:00 | 10:00 at Denver's offset that day (`"2026-01-15 10:00"` → -07:00) |
|
|
247
|
-
| a `format:` without `%z` (`:db`, `'%H:%M'`) | as above | 10:00 at -06:00; a date the format omits is *today in -06:00* | the same, at that date's offset; an omitted date is *today in Denver* |
|
|
248
|
-
| `"2026-10-22T10:00:00+02:00"`, `"… Z"`, `"… EST"` | its own offset | its own offset (unchanged) | its own offset (unchanged) |
|
|
249
|
-
| `"2026-10-22 10:00 XYZ"`, `"… America/Denver"` (a zone in the *string*) | `:time` process zone; `:datetime` UTC | refused — `zone:` won't override a stated zone | refused, likewise |
|
|
250
|
-
| `Time` / `DateTime` / TimeWithZone | instant and offset kept | instant and offset kept (not converted) | instant and offset kept (not converted) |
|
|
251
|
-
| `Date` | midnight: `:time` process zone, `:datetime` UTC | midnight at -06:00 | midnight at that day's offset |
|
|
252
|
-
| an epoch string under `format: '%s'` | that instant, in the process zone (`:time`) or UTC (`:datetime`) | that instant, at -06:00 | that instant, at Denver's offset at that instant |
|
|
253
|
-
| Integer (epoch seconds) | refused | refused | refused |
|
|
254
|
-
|
|
255
|
-
- **Accepted values:** `"UTC"` (the `:time` value is then `utc?`), fixed offsets
|
|
256
|
-
`"+HH:MM"` / `"-HH:MM"` from `-23:59` to `+23:59` (colon required), and IANA
|
|
257
|
-
`Area/Location` names in the zone database (`"America/Denver"`, `"Etc/UTC"`,
|
|
258
|
-
`"America/Argentina/Buenos_Aires"`). Anything else raises `ArgumentError` at
|
|
259
|
-
declaration, naming the option: `"utc"`, `"Z"`, `"-0600"`, an unknown name, and
|
|
260
|
-
abbreviations or legacy aliases with no `/` — `"MST"` is in the zone database,
|
|
261
|
-
but as a fixed -07:00, not Mountain time with DST, so it is refused rather than
|
|
262
|
-
quietly meaning something else.
|
|
263
|
-
- **Rails zone names are refused** (`"Mountain Time (US & Canada)"`). They are
|
|
264
|
-
ActiveSupport aliases that exist only when ActiveSupport is loaded, so accepting
|
|
265
|
-
them would make the same declaration valid in one process and invalid in another.
|
|
266
|
-
Use the IANA name they map to (`ActiveSupport::TimeZone::MAPPING[name]`).
|
|
267
|
-
- **Daylight-saving edges** (names only — a fixed offset has none):
|
|
268
|
-
- A wall-clock time the zone **skips** (`"2026-03-08 02:30"` in Denver, inside the
|
|
269
|
-
spring-forward hour) is refused: `could not be coerced: names a local time that
|
|
270
|
-
does not exist in America/Denver (skipped by a daylight-saving change)`. It names
|
|
271
|
-
no instant, like the 30th of February. ActiveSupport moves it an hour forward
|
|
272
|
-
(03:30); FieldStruct does not guess.
|
|
273
|
-
- A wall-clock time the zone **repeats** (`"2026-11-01 01:30"`, which happens at
|
|
274
|
-
-06:00 and again at -07:00) is read at the **daylight-time** offset, the earlier
|
|
275
|
-
instant — what ActiveSupport's `TimeWithZone` picks, so a Rails app sees the
|
|
276
|
-
same answer.
|
|
277
|
-
- A `Date` whose midnight the zone skips becomes the **first moment** of that day
|
|
278
|
-
(01:00 -03:00 in `America/Santiago` on 6 September 2026), as `Date#in_time_zone` does.
|
|
279
|
-
- **What you get back** is a plain `Time` (or `DateTime`) with that offset — never a
|
|
280
|
-
`TZInfo::TimeWithOffset`, and it does not remember the zone: `Time#zone` is `nil`
|
|
281
|
-
and adding a day keeps the offset rather than following DST. Re-assign to re-read.
|
|
282
|
-
- **Dependency:** the zone database is [tzinfo](https://github.com/tzinfo/tzinfo)'s
|
|
283
|
-
(a runtime dependency since 0.14), required only when a field declares a name — a
|
|
284
|
-
`"UTC"` or fixed-offset field never loads it. tzinfo reads the OS zoneinfo
|
|
285
|
-
(`/usr/share/zoneinfo`); on a system without it (Windows, slim containers) a
|
|
286
|
-
declaration raises `ArgumentError` saying to add the `tzinfo-data` gem.
|
|
287
|
-
- `zone:` has no effect with `format: :iso8601`, which requires an offset anyway.
|
|
288
|
-
It does not apply to `:date` (a date has no time of day to place).
|
|
289
|
-
|
|
290
|
-
<!-- doctest -->
|
|
291
|
-
```ruby
|
|
292
|
-
class Shift < FieldStruct::Base
|
|
293
|
-
required :starts, :time, zone: '-06:00'
|
|
294
|
-
optional :logged, :datetime, zone: 'UTC'
|
|
295
|
-
optional :ends, :time, zone: 'UTC', format: :db
|
|
296
|
-
optional :local, :time, zone: 'America/Denver'
|
|
223
|
+
Every type accepts `nil` and returns `nil`. "Missing" is what `required` rejects.
|
|
224
|
+
|
|
225
|
+
An option on a type that doesn't take it raises at declaration and lists the types that do:
|
|
226
|
+
|
|
227
|
+
<!-- generated: option-types -->
|
|
228
|
+
| Option | Types |
|
|
229
|
+
|---|---|
|
|
230
|
+
| `format:` | `:string`, `:immutable_string`, `:date`, `:time`, `:datetime`, `:uuid`, `:url`, `:email`, `:binary` |
|
|
231
|
+
| `enum:` | `:string`, `:immutable_string`, `:symbol`, `:uuid`, `:url`, `:email`, `:binary` |
|
|
232
|
+
| `strict:` | `:string`, `:immutable_string`, `:integer`, `:uuid`, `:url`, `:email`, `:binary` |
|
|
233
|
+
| `length:` | `:string`, `:immutable_string`, `:uuid`, `:url`, `:email`, `:binary` |
|
|
234
|
+
| `in:` | `:integer`, `:float`, `:big_decimal`, `:decimal`, `:date`, `:time`, `:datetime` |
|
|
235
|
+
| `base:` | `:integer` |
|
|
236
|
+
| `round:` | `:float`, `:big_decimal`, `:decimal` |
|
|
237
|
+
| `json:` | `:big_decimal`, `:decimal` |
|
|
238
|
+
| `values:` | `:boolean` |
|
|
239
|
+
| `zone:` | `:time`, `:datetime` |
|
|
240
|
+
| `of:` | `:array`, `:hash`, `:union` |
|
|
241
|
+
| `element:` | `:array`, `:hash` |
|
|
242
|
+
| `max_items:` | `:array` |
|
|
243
|
+
| `discriminator:` | `:union` |
|
|
244
|
+
<!-- end generated -->
|
|
245
|
+
|
|
246
|
+
### Strings
|
|
247
|
+
|
|
248
|
+
| Type | Coerces | Missing | Lot |
|
|
249
|
+
|---|---|---|---|
|
|
250
|
+
| `:string` | any value via `to_s` | nil, blank | `String` |
|
|
251
|
+
| `:immutable_string` | as `:string` | nil, blank | frozen copy |
|
|
252
|
+
| `:uuid` `:url` `:email` | as `:string`, and checks a default `format:` | nil, blank | `String` |
|
|
253
|
+
| `:binary` | any value via `to_s`, bytes as ASCII-8BIT | nil, empty | `String` |
|
|
254
|
+
|
|
255
|
+
Options: `format:` (a Regexp, or a preset name for `:uuid` `:url` `:email`), `enum:` (Array), `strict:` (`true` accepts
|
|
256
|
+
only String, Symbol, Integer or `to_str` objects).
|
|
257
|
+
|
|
258
|
+
| Type | Presets (`format: :name`) | Default |
|
|
259
|
+
|---|---|---|
|
|
260
|
+
| `:uuid` | `any_version` `v4` `v7` | `any_version` |
|
|
261
|
+
| `:url` | `http` `https_only` `any_scheme` | `http` |
|
|
262
|
+
| `:email` | `permissive` `default` `strict` | `default` |
|
|
263
|
+
|
|
264
|
+
```ruby run
|
|
265
|
+
require 'field_struct'
|
|
266
|
+
|
|
267
|
+
class Marker < FieldStruct::Base
|
|
268
|
+
optional :id, :uuid, format: :v4
|
|
269
|
+
optional :href, :url, format: :https_only
|
|
270
|
+
optional :mail, :email, format: :strict
|
|
271
|
+
optional :slug, :string, enum: %w[a b]
|
|
272
|
+
optional :note, :string, strict: true
|
|
273
|
+
optional :frozen, :immutable_string
|
|
297
274
|
end
|
|
298
275
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
276
|
+
Marker.new(slug: 'a').valid? # => true
|
|
277
|
+
Marker.new(slug: 'z').errors[:slug] # => ["is invalid"]
|
|
278
|
+
Marker.new(href: 'http://x.io').valid? # => false
|
|
279
|
+
Marker.new(note: 1.5).valid? # => false
|
|
280
|
+
Marker.new(frozen: +'x').frozen.frozen? # => true
|
|
281
|
+
Marker.new(slug: 12).slug # => "12"
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
`format:` is matched against the String form (`\A` and `\z` anchors are yours to write). An explicit
|
|
285
|
+
`enum:`/`format:` check is skipped for `nil`.
|
|
286
|
+
|
|
287
|
+
### Symbols
|
|
305
288
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
289
|
+
`:symbol` turns a String into a Symbol and keeps Symbols. Anything else is a coercion failure. `enum:` is checked after
|
|
290
|
+
coercion, so `'wild'` matches `enum: %i[wild bred]`.
|
|
291
|
+
|
|
292
|
+
### Numbers
|
|
293
|
+
|
|
294
|
+
| Type | Reads | Options |
|
|
295
|
+
|---|---|---|
|
|
296
|
+
| `:integer` | Integer; String in `base:` (default 10; `"010"` is 10, `"1_000"` is 1000); Float and Rational truncate toward zero | `in:` (Range or Array), `base:` (2..36), `strict:` |
|
|
297
|
+
| `:float` | Float; numeric Strings (`"1e3"`, `".5"`); anything `Float()` takes | `round:` (digits, half up), `in:` |
|
|
298
|
+
| `:decimal` / `:big_decimal` | BigDecimal; Float via 15 digits; numeric Strings | `round:`, `in:`, `json:` |
|
|
299
|
+
|
|
300
|
+
NaN and the infinities are always refused. `strict: true` on `:integer` accepts only whole numbers (`12.0` yes,
|
|
301
|
+
`12.7` no); Strings follow the normal rules.
|
|
302
|
+
|
|
303
|
+
```ruby run
|
|
304
|
+
require 'field_struct'
|
|
305
|
+
require 'bigdecimal'
|
|
306
|
+
|
|
307
|
+
class Gauge < FieldStruct::Base
|
|
308
|
+
optional :count, :integer, base: 16
|
|
309
|
+
optional :whole, :integer, strict: true
|
|
310
|
+
optional :temp, :float, round: 1, in: -90.0..60.0
|
|
311
|
+
optional :yield_kg, :decimal, round: 2
|
|
312
|
+
end
|
|
313
|
+
|
|
314
|
+
m = Gauge.new(count: '1A', whole: 12.0, temp: '21.46', yield_kg: '12.345')
|
|
315
|
+
m.count # => 26
|
|
316
|
+
m.whole # => 12
|
|
317
|
+
m.temp # => 21.5
|
|
318
|
+
m.yield_kg # => BigDecimal('12.35')
|
|
319
|
+
Gauge.new(whole: 12.7).valid? # => false
|
|
320
|
+
Gauge.new(temp: 100).errors[:temp] # => ["is invalid"]
|
|
321
|
+
Gauge.new(count: '12.5').valid? # => false
|
|
311
322
|
```
|
|
312
323
|
|
|
313
|
-
|
|
324
|
+
### Booleans
|
|
314
325
|
|
|
315
|
-
|
|
326
|
+
`true` / `false`, the integers `1` / `0`, and the Strings `true false 1 0` (any case, no trimming). `values:` swaps in
|
|
327
|
+
your own String vocabulary: a Hash `{truthy: [...], falsy: [...]}` or a preset (`:english_yes_no` = `:english`
|
|
328
|
+
= `true yes y on 1` / `false no n off 0, `:numeric` = `1` / `0`). The vocabulary only applies to Strings.
|
|
316
329
|
|
|
317
|
-
```ruby
|
|
318
|
-
|
|
319
|
-
immutable! # setters raise ImmutableError after initialize
|
|
320
|
-
frozen! # Ruby-freeze the instance at end of initialize (stackable with immutable!)
|
|
321
|
-
coercion_policy :replace # class-wide coercion-failure policy; inherited by subclasses
|
|
322
|
-
unknown_attributes :raise # reject unknown input keys (default :ignore = drop them)
|
|
330
|
+
```ruby run
|
|
331
|
+
require 'field_struct'
|
|
323
332
|
|
|
324
|
-
|
|
325
|
-
|
|
333
|
+
class Switches < FieldStruct::Base
|
|
334
|
+
optional :plain, :boolean
|
|
335
|
+
optional :english, :boolean, values: :english
|
|
336
|
+
optional :custom, :boolean, values: {truthy: %w[si], falsy: %w[no]}
|
|
337
|
+
end
|
|
326
338
|
|
|
327
|
-
|
|
339
|
+
Switches.new(plain: 'TRUE').plain # => true
|
|
340
|
+
Switches.new(english: 'Yes').english # => true
|
|
341
|
+
Switches.new(custom: 'si').custom # => true
|
|
342
|
+
Switches.new(plain: 'yes').valid? # => false
|
|
343
|
+
```
|
|
328
344
|
|
|
329
|
-
|
|
330
|
-
validate { |rec| rec.errors.add(:base, 'empty') if rec.title.to_s.empty? } # or block
|
|
345
|
+
### Any value
|
|
331
346
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
347
|
+
`:value` stores whatever it's given, untouched. Only nil is missing.
|
|
348
|
+
|
|
349
|
+
## Arrays, maps, nested structs, unions
|
|
350
|
+
|
|
351
|
+
Fields that hold other values: lists, maps with String keys, other structs, and one of several types.
|
|
352
|
+
|
|
353
|
+
### Arrays
|
|
354
|
+
|
|
355
|
+
`:array` needs `of:` (a type name, a struct class or a type class). Elements are coerced one by one; `nil` elements stay
|
|
356
|
+
`nil`. One bad element fails the whole array, and the message names the indexes (never the values). `[]` is missing.
|
|
357
|
+
`element:` passes options to every element.
|
|
358
|
+
|
|
359
|
+
```ruby run
|
|
360
|
+
require 'field_struct'
|
|
361
|
+
|
|
362
|
+
class Rack < FieldStruct::Base
|
|
363
|
+
required :ids, :array, of: :integer, element: {in: 1..99}
|
|
364
|
+
optional :emails, :array, of: :email
|
|
335
365
|
end
|
|
366
|
+
|
|
367
|
+
Rack.new(ids: %w[1 2 3]).ids # => [1, 2, 3]
|
|
368
|
+
Rack.new(ids: []).errors[:ids] # => ["is required"]
|
|
369
|
+
Rack.new(ids: [1, 'x', 'y']).errors[:ids].first # => "could not be coerced: elements at index 1, 2 (index 1 shown): Integer fields expect a base-10 integer, got a String that is not one"
|
|
370
|
+
Rack.new(ids: [1, 500]).errors[:ids] # => ["element at index 1 is invalid"]
|
|
371
|
+
Rack.new(ids: 'nope').valid? # => false
|
|
336
372
|
```
|
|
337
373
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
- `validate` runs at `valid?` (and at construct if any exist); convention is `errors.add(:base, ...)`; `errors[:base]` is cleared each `valid?` run.
|
|
374
|
+
`of:` must be given (`of: is required for Array fields`). An array of arrays is not supported. `max_items: N` caps the
|
|
375
|
+
length: a longer array gets the field error `has too many items (maximum is N)`.
|
|
341
376
|
|
|
342
|
-
###
|
|
377
|
+
### Maps
|
|
343
378
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
a trace. With `:raise`, `new` / `from_json` / `assign_attributes` / `with` fail with an
|
|
349
|
-
`UnknownAttributeError` whose `keys` name the extras (names only, never values).
|
|
379
|
+
`:hash` is a map with String keys: `of:` names the value type and `element:` passes options to every value, as for
|
|
380
|
+
arrays. Symbol keys become Strings; any other key class fails the whole map. `{}` is missing. Messages say how many
|
|
381
|
+
entries failed, never which key, since a key is input. A map of structs builds each value, and `errors.paths` names
|
|
382
|
+
the entry with its key.
|
|
350
383
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
drops its own unknown keys. The nested error propagates out of the parent's
|
|
354
|
-
`new` rather than going through the parent's `coercion_policy`.
|
|
355
|
-
- **`from_json` reverse-maps `serialize :json` names first**, so external names
|
|
356
|
-
(`"amountDecimal"`) are known keys there. Passing them to `new` raises, because
|
|
357
|
-
`new` takes canonical names.
|
|
358
|
-
- Keep `:ignore` where extra keys are expected and harmless, e.g. a struct reading
|
|
359
|
-
a few fields out of a large third-party payload.
|
|
384
|
+
```ruby run
|
|
385
|
+
require 'field_struct'
|
|
360
386
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
class Card < FieldStruct::Base
|
|
364
|
-
unknown_attributes :raise
|
|
365
|
-
required :last4, :string
|
|
387
|
+
class Buoy < FieldStruct::Base
|
|
388
|
+
required :metres, :float
|
|
366
389
|
end
|
|
367
390
|
|
|
368
|
-
class
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
required :card, Card
|
|
372
|
-
serialize :json, amount: 'amountDecimal'
|
|
391
|
+
class Mooring < FieldStruct::Base
|
|
392
|
+
optional :depths, :hash, of: :integer, element: {in: 0..90}
|
|
393
|
+
optional :buoys, :hash, of: Buoy
|
|
373
394
|
end
|
|
374
395
|
|
|
375
|
-
|
|
396
|
+
Mooring.new(depths: {north: '12', 'south' => 7}).depths # => {"north" => 12, "south" => 7}
|
|
397
|
+
Mooring.new(depths: {north: 200}).errors[:depths] # => ["1 entry is invalid"]
|
|
398
|
+
Mooring.new(depths: {1 => 3}).errors[:depths].first # => "could not be coerced: hash keys must be Strings or Symbols, got Integer"
|
|
399
|
+
Mooring.new(buoys: {'outer' => {}}).errors.paths # => {"buoys{\"outer\"}.metres" => ["is required"]}
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
### Mirrors
|
|
376
403
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
404
|
+
`mirror!` makes a struct a view other objects can be read into. A field of a mirror type (or an array or map of one)
|
|
405
|
+
takes any object besides a Hash or an instance: the mirror calls one public reader per declared field, by field name,
|
|
406
|
+
and builds through `new`, so only declared fields are read and everything is coerced as usual. A source missing a
|
|
407
|
+
reader always raises, whatever the policy or default. `mirror?` tells you whether a class (or an ancestor) is one.
|
|
408
|
+
|
|
409
|
+
```ruby run
|
|
410
|
+
require 'field_struct'
|
|
411
|
+
|
|
412
|
+
class GaugeView < FieldStruct::Base
|
|
413
|
+
mirror!
|
|
414
|
+
required :celsius, :float
|
|
381
415
|
end
|
|
382
|
-
typo.keys # => [:ammount]
|
|
383
|
-
typo.message # "unknown attribute(s) for Charge: :ammount"
|
|
384
416
|
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
end
|
|
390
|
-
nested.keys # => [:cvv]
|
|
391
|
-
nested.message # "unknown attribute(s) for Card: :cvv"
|
|
392
|
-
```
|
|
393
|
-
|
|
394
|
-
---
|
|
395
|
-
|
|
396
|
-
## Instance surface
|
|
397
|
-
|
|
398
|
-
```ruby
|
|
399
|
-
u = User.new(name: 'Alice', age: '30') # Hash arg; Symbol or String keys
|
|
400
|
-
u.name; u.age = 31 # typed reader; permissive setter (coerces)
|
|
401
|
-
u.attributes # => { name: "Alice", age: 31 } (alias: to_h)
|
|
402
|
-
u.attribute_names # => [:name, :age]
|
|
403
|
-
u.valid? # runs cross-field validators, then errors.empty?
|
|
404
|
-
u.invalid?
|
|
405
|
-
u.errors # FieldStruct::Errors
|
|
406
|
-
u.inspect # #<User name: "Alice" age: 31>; an invalid instance appends
|
|
407
|
-
# `errors: {name: ["is required"]}` so it never looks fine
|
|
408
|
-
u == other # value equality (same class + same attributes; errors ignored)
|
|
409
|
-
u.as_json # JSON-ready Hash with :json mapping applied
|
|
410
|
-
u.to_json # String (via Oj)
|
|
411
|
-
User.from_json(str) # parse + reverse-map :json keys -> instance
|
|
412
|
-
u.assign_attributes(age: 40) # bulk update through the setter pipeline
|
|
413
|
-
u.with(age: 41) # NEW instance with age changed; u untouched
|
|
414
|
-
case u; in { name: 'Alice', age: } then age; end # pattern matching
|
|
415
|
-
```
|
|
416
|
-
|
|
417
|
-
### Copying with changes (`with`)
|
|
418
|
-
|
|
419
|
-
`with(**changes)` returns a new instance of the receiver's class with the given
|
|
420
|
-
attributes changed, like `Data#with`. The receiver is never modified, so it is the
|
|
421
|
-
way to "update" an `immutable!` or `frozen!` instance.
|
|
422
|
-
|
|
423
|
-
- **Changed fields go through the setter pipeline**: coercion, the field's
|
|
424
|
-
`coercion_policy` (under `:raise` the `CoercionError` propagates and no copy is
|
|
425
|
-
returned), and that field's errors rewritten. Cross-field `validate` blocks rerun.
|
|
426
|
-
- **Unchanged fields are carried over as they are**, errors included, exactly as
|
|
427
|
-
`dup` copies them. Callable defaults are not called again.
|
|
428
|
-
- **Shallow**, like `dup`: an unchanged nested struct or array is the *same object*
|
|
429
|
-
in both instances. Mutating one through the other is visible in both.
|
|
430
|
-
- **Unknown keys** follow `unknown_attributes` (dropped by default, `UnknownAttributeError`
|
|
431
|
-
under `:raise`). String keys work too: `with('age' => 41)`.
|
|
432
|
-
- **Keywords only**: `with({age: 41})` raises `ArgumentError`; splat a Hash with
|
|
433
|
-
`with(**hash)`. `with` with no changes returns an equal copy, not `self`.
|
|
434
|
-
- The copy is immutable when the class is, and frozen when the receiver is
|
|
435
|
-
frozen. `with` (and `dup`, which it relies on) are reserved field names.
|
|
436
|
-
|
|
437
|
-
<!-- doctest -->
|
|
438
|
-
```ruby
|
|
439
|
-
class Point < FieldStruct::Base
|
|
440
|
-
immutable!
|
|
441
|
-
required :x, :integer
|
|
442
|
-
required :y, :integer
|
|
417
|
+
class SiteView < FieldStruct::Base
|
|
418
|
+
mirror!
|
|
419
|
+
required :code, :string
|
|
420
|
+
optional :gauges, :array, of: GaugeView, max_items: 2
|
|
443
421
|
end
|
|
444
422
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
423
|
+
class Report < FieldStruct::Base
|
|
424
|
+
required :site, SiteView
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
Gauge = Struct.new(:celsius, :serial)
|
|
428
|
+
Site = Struct.new(:code, :gauges, :keeper_phone)
|
|
429
|
+
|
|
430
|
+
report = Report.new(site: Site.new('PK-7', [Gauge.new('4.5', 'g1')], '555'))
|
|
431
|
+
SiteView.mirror? # => true
|
|
432
|
+
report.site.as_json # => {code: "PK-7", gauges: [{celsius: 4.5}]}
|
|
433
|
+
Report.new(site: Site.new('PK-8', [Gauge.new(1, 'a')] * 3, nil)).site.errors[:gauges] # => ["has too many items (maximum is 2)"]
|
|
434
|
+
|
|
435
|
+
begin
|
|
436
|
+
Report.new(site: Gauge.new(2.0, 'g2'))
|
|
437
|
+
rescue ArgumentError => e
|
|
438
|
+
e.message # => "SiteView mirrors Gauge, but Gauge has no public readers for :code, :gauges"
|
|
439
|
+
end
|
|
452
440
|
```
|
|
453
441
|
|
|
454
|
-
`
|
|
455
|
-
`
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
messages pass through unprefixed).
|
|
442
|
+
An array of mirrors also takes a collection that isn't an Array. One whose `loaded?` is `true` is read with `to_a`.
|
|
443
|
+
Anything else that answers `first` (a lazy relation, say) needs `max_items:` and is read with `first(max_items + 1)`,
|
|
444
|
+
so going over is an error, never a silent cut. Without `max_items:` it raises `set max_items: on Report#gauges, or
|
|
445
|
+
load the relation yourself`. A union member never reads; a union still takes a Hash or an instance.
|
|
459
446
|
|
|
460
|
-
|
|
447
|
+
### Nested structs
|
|
461
448
|
|
|
462
|
-
|
|
449
|
+
A field typed with a struct class takes an instance or a Hash. Passing a Hash builds the struct, even an invalid one;
|
|
450
|
+
the parent field then reads `"is invalid"`.
|
|
463
451
|
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
- **Required + missing** → `errors.add(name, 'is required')`.
|
|
467
|
-
- **Present but invalid** → `errors.add(name, 'is invalid')`. "Invalid" = `format:`
|
|
468
|
-
regex mismatch, `enum:`/`in:` violation, an invalid nested struct, or an array with
|
|
469
|
-
an invalid element. An array element breaking its `element:` `format:`/`enum:`/`in:`
|
|
470
|
-
is reported by index: `'element at index 2 is invalid'`. So **"required" means present *and* valid**.
|
|
471
|
-
- **Validity is separate from construction.** A field can hold `nil`/raw even when
|
|
472
|
-
required — see coercion policy below. Always gate on `valid?`, don't assume a
|
|
473
|
-
required reader is non-nil.
|
|
452
|
+
```ruby run
|
|
453
|
+
require 'field_struct'
|
|
474
454
|
|
|
475
|
-
|
|
455
|
+
class Bed < FieldStruct::Base
|
|
456
|
+
required :habitat, :string
|
|
457
|
+
optional :plot_no, :string
|
|
458
|
+
end
|
|
459
|
+
|
|
460
|
+
class Gardener < FieldStruct::Base
|
|
461
|
+
required :name, :string
|
|
462
|
+
optional :border, Bed
|
|
463
|
+
optional :rotation, :array, of: Bed
|
|
464
|
+
end
|
|
465
|
+
|
|
466
|
+
gardener = Gardener.new(name: 'Ivy', border: {habitat: 'Fen'}, rotation: [{habitat: 'Heath'}, Bed.new(habitat: 'Moor')])
|
|
467
|
+
gardener.border.class # => Bed
|
|
468
|
+
gardener.rotation.map(&:habitat) # => ["Heath", "Moor"]
|
|
469
|
+
Gardener.new(name: 'Ivy', border: {plot_no: '1'}).errors[:border] # => ["is invalid"]
|
|
470
|
+
Gardener.new(name: 'Ivy', border: 5).errors[:border].first.start_with?('could not be coerced') # => true
|
|
471
|
+
```
|
|
476
472
|
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
invalid nested struct or array element when the nested value is assigned. **It
|
|
480
|
-
doesn't watch it afterwards.** Mutating a nested struct, or an array element, in
|
|
481
|
-
place leaves the parent's errors as they were, in both directions:
|
|
473
|
+
Validity is computed on assignment. Changing a nested object afterwards doesn't refresh the parent: re-assign it, or use
|
|
474
|
+
`with`.
|
|
482
475
|
|
|
483
|
-
|
|
484
|
-
- stays invalid after a nested problem is fixed in place.
|
|
476
|
+
### Unions
|
|
485
477
|
|
|
486
|
-
|
|
487
|
-
|
|
478
|
+
`:union` takes `of: [...]` (two or more registered names or struct classes). Members are tried in order and the first
|
|
479
|
+
that accepts wins, so order matters. A union can't hold an `:array` bred.
|
|
488
480
|
|
|
489
|
-
|
|
490
|
-
|
|
481
|
+
```ruby run
|
|
482
|
+
require 'field_struct'
|
|
491
483
|
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
484
|
+
class Survey < FieldStruct::Base
|
|
485
|
+
optional :ref, :union, of: %i[integer string]
|
|
486
|
+
optional :tag, :union, of: %i[string integer]
|
|
487
|
+
optional :flag, :union, of: %i[integer boolean]
|
|
496
488
|
end
|
|
497
489
|
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
490
|
+
Survey.new(ref: '42').ref # => 42
|
|
491
|
+
Survey.new(tag: '42').tag # => "42"
|
|
492
|
+
Survey.new(flag: 'maybe').valid? # => false
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
## Dates, times, zones
|
|
496
|
+
|
|
497
|
+
| Type | Reads | Lot |
|
|
498
|
+
|---|---|---|
|
|
499
|
+
| `:date` | String, Date, DateTime, Time | `Date` (a Time or DateTime keeps its own wall-clock day) |
|
|
500
|
+
| `:time` | String, Time, DateTime, Date | `Time` |
|
|
501
|
+
| `:datetime` | String, DateTime, Time, Date | `DateTime` |
|
|
502
|
+
|
|
503
|
+
Without `format:`, a String must name a whole day (year, month and day) that exists. Integers are refused. `format:`
|
|
504
|
+
is either a strptime String or a preset (`:iso8601` is RFC 3339, parsed by the gem itself):
|
|
505
|
+
|
|
506
|
+
| Preset | `:date` | `:time` / `:datetime` |
|
|
507
|
+
|---|---|---|
|
|
508
|
+
| `iso8601` | `2026-07-03` | `2026-07-03T10:30:00-06:00`, `...Z`, fractions allowed |
|
|
509
|
+
| `us` | `%m/%d/%Y` | |
|
|
510
|
+
| `eu` | `%d/%m/%Y` | |
|
|
511
|
+
| `rfc2822` | | `%a, %d %b %Y %H:%M:%S %z` |
|
|
512
|
+
| `db` | | `%Y-%m-%d %H:%M:%S` |
|
|
513
|
+
|
|
514
|
+
A declared format must match the whole string, and it is also what `as_json` writes. `in:` takes a Range or an Array.
|
|
515
|
+
`zone:` says which zone a zone-less string means: `"UTC"`, an offset like `"-06:00"`, or an IANA name
|
|
516
|
+
(`"America/Denver"`). It never overrides an offset the input carries.
|
|
517
|
+
|
|
518
|
+
```ruby run
|
|
519
|
+
require 'field_struct'
|
|
520
|
+
|
|
521
|
+
class Visit < FieldStruct::Base
|
|
522
|
+
optional :day, :date, format: :us, in: Date.new(2026, 1, 1)..Date.new(2026, 12, 31)
|
|
523
|
+
optional :starts, :time, zone: 'America/Denver'
|
|
524
|
+
optional :ends, :datetime, format: :iso8601
|
|
501
525
|
end
|
|
502
526
|
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
527
|
+
shift = Visit.new(day: '07/03/2026', starts: '2026-07-01 10:00', ends: '2026-07-01T10:00:00-06:00')
|
|
528
|
+
shift.day.iso8601 # => "2026-07-03"
|
|
529
|
+
shift.starts.utc_offset # => -21600
|
|
530
|
+
Visit.new(starts: '2026-01-15 10:00').starts.utc_offset # => -25200
|
|
531
|
+
shift.as_json[:day] # => "07/03/2026"
|
|
532
|
+
shift.as_json[:ends] # => "2026-07-01T10:00:00-06:00"
|
|
533
|
+
Visit.new(day: '2026-02-30').valid? # => false
|
|
534
|
+
# Denver skips 02:30 on 2026-03-08
|
|
535
|
+
Visit.new(starts: '2026-03-08 02:30').valid? # => false
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
The result is a plain `Time` or `DateTime` with the right offset; it doesn't remember the zone. The zone database
|
|
539
|
+
(`tzinfo`) is loaded only when a field names an IANA zone.
|
|
508
540
|
|
|
509
|
-
|
|
510
|
-
person.valid? # => false
|
|
511
|
-
person.errors[:address] # => ['is invalid']
|
|
541
|
+
## Class settings
|
|
512
542
|
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
543
|
+
| Macro | Values | Default |
|
|
544
|
+
|---|---|---|
|
|
545
|
+
| `coercion_policy` | `:keep_raw` `:replace` `:raise` | `:keep_raw` |
|
|
546
|
+
| `unknown_attributes` | `:ignore` `:raise` | `:ignore` |
|
|
547
|
+
| `json_omit` | `:none` `:unset` (see JSON) | `:none` |
|
|
548
|
+
| `immutable!` | setters raise `ImmutableError` after `new` | off |
|
|
549
|
+
| `frozen!` | instances are frozen at the end of `new` | off |
|
|
550
|
+
| `mirror!` | fields of this type read other objects into it (see Mirrors); read with `mirror?` | off |
|
|
551
|
+
| `serialize :format, field: 'name'` | maps field names for a format (see JSON) | none |
|
|
552
|
+
| `validate :method, ...` / `validate { |record| ... }` | cross-field checks (see Validation) | none |
|
|
517
553
|
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
554
|
+
Rules are inherited; a subclass can change its own without touching the parent. `immutable?` and
|
|
555
|
+
`frozen_on_construct?` read the flags.
|
|
556
|
+
|
|
557
|
+
```ruby run
|
|
558
|
+
require 'field_struct'
|
|
559
|
+
|
|
560
|
+
class Rules < FieldStruct::Base
|
|
561
|
+
coercion_policy :replace
|
|
562
|
+
unknown_attributes :raise
|
|
563
|
+
immutable!
|
|
564
|
+
required :level, :integer
|
|
565
|
+
end
|
|
566
|
+
|
|
567
|
+
Rules.new(level: 'x').level # => nil
|
|
568
|
+
begin
|
|
569
|
+
Rules.new(level: 1, extra: 2)
|
|
570
|
+
rescue FieldStruct::UnknownAttributeError => e
|
|
571
|
+
e.keys # => [:extra]
|
|
572
|
+
end
|
|
573
|
+
begin
|
|
574
|
+
Rules.new(level: 1).level = 2
|
|
575
|
+
rescue FieldStruct::ImmutableError => e
|
|
576
|
+
e.message # => "Rules is immutable; cannot reassign level"
|
|
577
|
+
end
|
|
578
|
+
Rules.new(level: 1).with(level: 2).level # => 2
|
|
523
579
|
```
|
|
524
580
|
|
|
525
|
-
|
|
526
|
-
|
|
581
|
+
## Validation
|
|
582
|
+
|
|
583
|
+
`validate` registers methods (called with no arguments) or a block (called with the record). Validators run after the
|
|
584
|
+
per-field checks, once at the end of `new` and `with`, and again on every `valid?`. Before each run `errors[:base]` is
|
|
585
|
+
cleared, so cross-field messages belong under `:base`. A validator that adds to a named field has to clean up after
|
|
586
|
+
itself.
|
|
527
587
|
|
|
528
|
-
|
|
588
|
+
```ruby run
|
|
589
|
+
require 'field_struct'
|
|
529
590
|
|
|
530
|
-
|
|
591
|
+
class Bracket < FieldStruct::Base
|
|
592
|
+
required :low, :integer
|
|
593
|
+
required :high, :integer
|
|
594
|
+
validate :ordered
|
|
595
|
+
validate { |span| span.errors.add(:base, 'both are zero') if span.low == 0 && span.high == 0 }
|
|
596
|
+
|
|
597
|
+
def ordered
|
|
598
|
+
errors.add(:base, 'high must be above low') if low && high && high <= low
|
|
599
|
+
end
|
|
600
|
+
end
|
|
601
|
+
|
|
602
|
+
Bracket.new(low: 3, high: 1).errors[:base] # => ["high must be above low"]
|
|
603
|
+
Bracket.new(low: 0, high: 0).errors[:base] # => ["high must be above low", "both are zero"]
|
|
604
|
+
Bracket.new(low: 1, high: 2).valid? # => true
|
|
605
|
+
span = Bracket.new(low: 1, high: 2)
|
|
606
|
+
span.high = 0
|
|
607
|
+
span.valid? # => false
|
|
608
|
+
```
|
|
531
609
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
| `:keep_raw` (default) | the raw input | yes (`could not be coerced: …`) | nothing lost; inspect & fix |
|
|
535
|
-
| `:replace` | `nil` | yes | clean slate |
|
|
536
|
-
| `:raise` | — | — | raises `FieldStruct::CoercionError` |
|
|
610
|
+
A validator must cope with nil fields, because the record may be invalid. A subclass gets a copy of its parent's
|
|
611
|
+
validators and adds its own.
|
|
537
612
|
|
|
538
|
-
|
|
539
|
-
`could not be coerced: Integer fields expect a base-10 integer, got a String that is
|
|
540
|
-
not one`; under `:raise`, `could not coerce String input for cents: …`.
|
|
613
|
+
## JSON
|
|
541
614
|
|
|
542
|
-
|
|
615
|
+
`as_json` returns a Hash with Symbol keys, every field present (unless the class says `json_omit :unset`, below). `to_json` is `Oj.dump(as_json, mode: :compat)`, except
|
|
616
|
+
that decimals go out as JSON numbers.
|
|
617
|
+
`from_json(string)` parses with Oj (fractions and exponents arrive as BigDecimal) and builds through `new`, so every
|
|
618
|
+
rule above applies.
|
|
543
619
|
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
`ArgumentError`/`TypeError`, `from_json`'s errors), and not their `cause` chain, which
|
|
547
|
-
error reporters print. Kernel conversion errors (`invalid value for Integer(): "…"`)
|
|
548
|
-
are dropped from the chain; an invalid-JSON error from `from_json` keeps Oj's error
|
|
549
|
-
class and position but not the quoted input. Declared schema (a format, a boolean's
|
|
550
|
-
accepted strings, a field name) is still named. A custom type owns its own messages:
|
|
551
|
-
raise with the value's class, not its `inspect`.
|
|
620
|
+
`serialize :json, internal_name: 'external_name'` renames keys in both directions, recursively through nested structs
|
|
621
|
+
and arrays of structs. Canonical names are also accepted on input.
|
|
552
622
|
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
structs and arrays of them. `nil` still shows, so a missing value stays visible:
|
|
623
|
+
```ruby run
|
|
624
|
+
require 'field_struct'
|
|
556
625
|
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
626
|
+
class Dispatch < FieldStruct::Base
|
|
627
|
+
required :species, :string
|
|
628
|
+
optional :cost, :decimal
|
|
629
|
+
optional :sent_at, :datetime, format: :iso8601
|
|
630
|
+
serialize :json, sent_at: 'sentAt'
|
|
631
|
+
end
|
|
632
|
+
|
|
633
|
+
dispatch = Dispatch.from_json('{"species":"Hi","cost":2.5,"sentAt":"2026-03-04T05:06:07Z"}')
|
|
634
|
+
dispatch.cost # => BigDecimal('2.5')
|
|
635
|
+
dispatch.sent_at.year # => 2026
|
|
636
|
+
dispatch.as_json # => {species: "Hi", cost: "2.5", sentAt: "2026-03-04T05:06:07Z"}
|
|
637
|
+
dispatch.to_json # => "{\"species\":\"Hi\",\"cost\":2.5,\"sentAt\":\"2026-03-04T05:06:07Z\"}"
|
|
638
|
+
Dispatch.from_json(dispatch.to_json) == dispatch # => true
|
|
639
|
+
|
|
640
|
+
begin
|
|
641
|
+
Dispatch.from_json('[1]')
|
|
642
|
+
rescue ArgumentError => e
|
|
643
|
+
e.message # => "from_json expects a JSON object root, got Array"
|
|
644
|
+
end
|
|
645
|
+
|
|
646
|
+
begin
|
|
647
|
+
Dispatch.from_json('{oops')
|
|
648
|
+
rescue EncodingError => e
|
|
649
|
+
e.message.start_with?('from_json could not parse its input as JSON') # => true
|
|
650
|
+
end
|
|
571
651
|
```
|
|
572
652
|
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
653
|
+
`to_json` writes a decimal as a JSON number with every digit (`BigDecimal('12.50')` is `12.5`), in arrays, maps,
|
|
654
|
+
nested structs and `:value` fields too. `as_json` keeps it a String, so another encoder that writes the Hash gets
|
|
655
|
+
strings. A field declared `json: :string` (or `element: {json: :string}` on an array or map of decimals) keeps the
|
|
656
|
+
string in `to_json` too, for values that must survive JavaScript's float parsing; `json:` takes `:number` or `:string`.
|
|
657
|
+
A `Types::BigDecimal` subclass can change the default for all its fields by answering `json_default` with `:string`.
|
|
658
|
+
`from_json` reads either form back to the same BigDecimal. Dates and times go out with the field's `format:`. A `:value` field
|
|
659
|
+
round-trips only if its content is plain JSON.
|
|
578
660
|
|
|
579
|
-
|
|
661
|
+
A `:value` field holding some other object writes that object's own `as_json`. Pass `describe_foreign: true` to write a
|
|
662
|
+
short description instead (`"#<Kiln id=12>"`); only the object's `class` and `id` are read.
|
|
580
663
|
|
|
581
|
-
|
|
664
|
+
```ruby run
|
|
665
|
+
require 'field_struct'
|
|
582
666
|
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
667
|
+
class Kiln
|
|
668
|
+
attr_reader :id
|
|
669
|
+
def initialize(id) = @id = id
|
|
670
|
+
def as_json(*) = { 'id' => id, 'firing_log' => ['cone 6'] }
|
|
586
671
|
end
|
|
587
672
|
|
|
588
|
-
class
|
|
589
|
-
|
|
590
|
-
optional :address, Address # nested: Hash or Address instance
|
|
591
|
-
optional :aliases, :array, of: :string # array of scalars
|
|
592
|
-
optional :homes, :array, of: Address # array of nested (each coerced + validated)
|
|
593
|
-
required :id, :union, of: %i[string integer] # union: first member that accepts it
|
|
673
|
+
class Shift < FieldStruct::Base
|
|
674
|
+
optional :kiln, :value
|
|
594
675
|
end
|
|
595
676
|
|
|
596
|
-
|
|
677
|
+
shift = Shift.new(kiln: Kiln.new(12))
|
|
678
|
+
shift.as_json # => {kiln: {"id" => 12, "firing_log" => ["cone 6"]}}
|
|
679
|
+
shift.as_json(describe_foreign: true) # => {kiln: "#<Kiln id=12>"}
|
|
597
680
|
```
|
|
598
681
|
|
|
599
|
-
|
|
600
|
-
|
|
682
|
+
`json_omit :unset` leaves a field out of `as_json` and `to_json` when the caller didn't give it and it's `nil`.
|
|
683
|
+
Defaults are still written, and so is a `nil` the caller gave. A nested struct follows its own class's setting.
|
|
601
684
|
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
When several are refused, every index is listed and the first one's reason is
|
|
605
|
-
shown — `elements at index 1, 4, 7 (index 1 shown): …` — up to five indexes, then
|
|
606
|
-
a count (`elements at index 0, 1, 2, 3, 4 and 15 more (index 0 shown): …`). The
|
|
607
|
-
same message reaches every `coercion_policy`, `:raise` included.
|
|
685
|
+
```ruby run
|
|
686
|
+
require 'field_struct'
|
|
608
687
|
|
|
609
|
-
|
|
688
|
+
class Sounding < FieldStruct::Base
|
|
689
|
+
json_omit :unset
|
|
690
|
+
optional :station, :string
|
|
691
|
+
optional :tethered, :boolean, default: true
|
|
692
|
+
optional :burst_m, :integer
|
|
693
|
+
end
|
|
694
|
+
|
|
695
|
+
Sounding.json_omit # => :unset
|
|
696
|
+
Sounding.new(station: 'Ridge').as_json # => {station: "Ridge", tethered: true}
|
|
697
|
+
Sounding.new(station: 'Ridge', burst_m: nil).as_json # => {station: "Ridge", tethered: true, burst_m: nil}
|
|
698
|
+
```
|
|
610
699
|
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
`
|
|
615
|
-
`coercion_policy:`, `sensitive:`, …).
|
|
700
|
+
For an update (PATCH) body, `Klass.partial` gives a sibling class, `Klass::Partial`, built on the first call: the same
|
|
701
|
+
fields and mappings, every field optional with no default, and `json_omit :unset`, so its JSON holds exactly what the
|
|
702
|
+
caller sent. Type checks and field options still apply; cross-field `validate` rules and methods you defined on
|
|
703
|
+
`Klass` (reader overrides too) don't carry over. It is not a subclass of `Klass`.
|
|
616
704
|
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
705
|
+
```ruby run
|
|
706
|
+
require 'field_struct'
|
|
707
|
+
|
|
708
|
+
class Tower < FieldStruct::Base
|
|
709
|
+
required :callsign, :string
|
|
710
|
+
required :height_m, :integer, default: 30
|
|
711
|
+
serialize :json, height_m: 'heightM'
|
|
623
712
|
end
|
|
624
713
|
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
Batch.new(days: ['22/10/2026']).as_json[:days] # => ['22/10/2026']
|
|
631
|
-
Batch.metadata.to_h[:ids][:options] # => { of_type: 'Integer', element: { strict: true, base: 16 } }
|
|
714
|
+
patch = Tower.partial.new(height_m: '45')
|
|
715
|
+
patch.valid? # => true
|
|
716
|
+
patch.as_json # => {heightM: 45}
|
|
717
|
+
Tower.partial.equal?(Tower::Partial) # => true
|
|
718
|
+
patch.is_a?(Tower) # => false
|
|
632
719
|
```
|
|
633
720
|
|
|
634
|
-
|
|
635
|
-
error a scalar field would get, prefixed with the field: `element: { base: '16' }`
|
|
636
|
-
raises `in element: of array field :ids, base: on Integer expects Integer, got String
|
|
637
|
-
("16")`. A key the element type doesn't take raises, listing the ones it does
|
|
638
|
-
(`round: is not an Integer option. Integer accepts: in, base, strict.`) — unlike a
|
|
639
|
-
field, `element:` passes nothing through. A temporal element's `format:` is also
|
|
640
|
-
what `to_json` writes, so `from_json` reads it back. `describe` lists what each
|
|
641
|
-
array's elements accept, by name (`element accepts in, base, strict`); the shapes
|
|
642
|
-
are the element type's own (`FieldStruct::Types::Integer.option_schema`).
|
|
643
|
-
Not supported: `element:` on an `:array` of arrays, and on a nested struct element
|
|
644
|
-
(a struct takes no options).
|
|
721
|
+
## Introspection
|
|
645
722
|
|
|
646
|
-
|
|
723
|
+
```ruby run
|
|
724
|
+
require 'field_struct'
|
|
647
725
|
|
|
648
|
-
|
|
726
|
+
class Chore < FieldStruct::Base
|
|
727
|
+
required :species, :string, description: 'What to do'
|
|
728
|
+
optional :done, :boolean
|
|
729
|
+
optional :tags, :array, of: :string
|
|
730
|
+
end
|
|
731
|
+
|
|
732
|
+
puts Chore.describe
|
|
733
|
+
Chore.metadata[:species].required? # => true
|
|
734
|
+
Chore.metadata[:species].type # => FieldStruct::Types::String
|
|
735
|
+
Chore.metadata[:species].description # => "What to do"
|
|
736
|
+
Chore.metadata[:tags].options[:of_type] # => FieldStruct::Types::String
|
|
737
|
+
Chore.metadata.names # => [:species, :done, :tags]
|
|
738
|
+
Chore.metadata.to_h[:done][:required] # => false
|
|
739
|
+
Chore.new(species: 'x').inspect # => '#<Chore species: "x", done: nil, tags: nil>'
|
|
740
|
+
Chore.metadata.each.map(&:name) # => [:species, :done, :tags]
|
|
741
|
+
Chore.metadata[:done].nullable? # => false
|
|
742
|
+
Chore.metadata[:done].sensitive? # => false
|
|
743
|
+
Chore.metadata[:done].type_instance.class # => FieldStruct::Types::Boolean
|
|
744
|
+
Chore.metadata.serializations # => {}
|
|
745
|
+
Chore.metadata.reverse_serialization(:json) # => {}
|
|
746
|
+
Chore.validators # => []
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
`metadata.serializations` holds the key mappings declared with `serialize`, and `reverse_serialization(:json)` maps
|
|
750
|
+
an external key back to its field. `validators` lists the blocks given to `validate`, inherited as a copy.
|
|
751
|
+
|
|
752
|
+
For Rails helpers a struct answers `model_name` and `to_model` (itself); it isn't a form object and has no
|
|
753
|
+
persistence methods:
|
|
649
754
|
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
restore).
|
|
653
|
-
- Conversions in `as_json`: `Date`/`Time`/`DateTime` → ISO-8601 (or the field's
|
|
654
|
-
`format:`), `BigDecimal` → plain string, `Symbol` → String, arrays/nested recurse.
|
|
655
|
-
- `from_json` parses JSON numbers with a fraction or exponent as `BigDecimal`, so a
|
|
656
|
-
`:decimal` gets the exact digits sent (`1234567890123.4567`, not `…123.46`).
|
|
657
|
-
`:float` still holds a Float; a `:value` field (and numbers inside its Hashes and
|
|
658
|
-
Arrays) holds the `BigDecimal` — which `to_json` writes back as a string.
|
|
755
|
+
```ruby run
|
|
756
|
+
require 'field_struct'
|
|
659
757
|
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
class U < FieldStruct::Base
|
|
663
|
-
required :first, :string
|
|
664
|
-
serialize :json, first: 'firstName'
|
|
758
|
+
class Seedling < FieldStruct::Base
|
|
759
|
+
optional :trays, :integer
|
|
665
760
|
end
|
|
666
|
-
|
|
667
|
-
|
|
761
|
+
|
|
762
|
+
Seedling.model_name.singular # => "seedling"
|
|
763
|
+
Seedling.model_name.plural # => "seedlings"
|
|
764
|
+
Seedling.new.model_name.singular # => "seedling"
|
|
765
|
+
Seedling.model_name.param_key # => "seedling"
|
|
766
|
+
seedling = Seedling.new
|
|
767
|
+
seedling.to_model.equal?(seedling) # => true
|
|
668
768
|
```
|
|
669
769
|
|
|
670
|
-
|
|
770
|
+
`param_key` is the key `form_with model: seedling, url: '/seedlings'` nests the fields under (`seedling[trays]`). It's
|
|
771
|
+
the last segment only, so `Nursery::Seedling` is `"seedling"` too; pass `scope:` when two classes end the same way.
|
|
772
|
+
Give `form_with` a `url:`, since a struct has no routes or `persisted?`.
|
|
773
|
+
|
|
774
|
+
`FieldStruct::Introspection.properties(klass, serialization: :json)` walks a struct for code that exports it to
|
|
775
|
+
another schema language (JSON Schema, Avro, Protobuf); it returns `Property` objects with `field`, `key` and a `node`
|
|
776
|
+
(`ScalarNode`, `ArrayNode`, `MapNode`, `UnionNode` or `StructNode`; a `UnionNode` lists its `members`, and an
|
|
777
|
+
`ArrayNode` or `MapNode` its `element`).
|
|
778
|
+
`FieldStruct::Introspection.named?(klass)` says whether a class can name a definition (false for anonymous classes).
|
|
779
|
+
`FieldStruct.use_alias!(:FS)` makes `FS` mean `FieldStruct` and switches every `inspect` to it; `FieldStruct.inspect_namespace`
|
|
780
|
+
returns the prefix in use (`"FieldStruct"` until then).
|
|
781
|
+
|
|
782
|
+
## Type signatures
|
|
671
783
|
|
|
672
|
-
|
|
784
|
+
The gem ships `sig/field_struct.rbs`. For your own models:
|
|
673
785
|
|
|
674
|
-
|
|
675
|
-
|
|
786
|
+
```ruby run
|
|
787
|
+
require 'field_struct'
|
|
788
|
+
|
|
789
|
+
class Plant < FieldStruct::Base
|
|
790
|
+
required :species, :string
|
|
791
|
+
optional :leaves, :integer
|
|
792
|
+
optional :tags, :array, of: :string
|
|
793
|
+
optional :rating, :union, of: %i[integer float]
|
|
794
|
+
end
|
|
676
795
|
|
|
677
|
-
|
|
678
|
-
|
|
796
|
+
puts FieldStruct::RBS.generate(Plant).lines.drop(3).first(6)
|
|
797
|
+
FieldStruct::RBS.type_for(Plant.metadata[:leaves]) # => "::Integer?"
|
|
798
|
+
FieldStruct::RBS.type_for(Plant.metadata[:species]) # => "::String"
|
|
799
|
+
FieldStruct::RBS.type_for(Plant.metadata[:species], nullable: true) # => "::String?"
|
|
800
|
+
FieldStruct::RBS.type_for(Plant.metadata[:rating]) # => "(::Integer | ::Float)?"
|
|
801
|
+
```
|
|
802
|
+
|
|
803
|
+
Readers of a required field have no `?`; writers always accept `nil`. The types describe a *valid* instance: an invalid one
|
|
804
|
+
can hold other values, so check `valid?`. Override a field with `rbs_type: '::Pathname'`, or give a custom type an
|
|
805
|
+
`rbs_type` method. Scalar array elements are nullable (`::Array[::String?]`).
|
|
806
|
+
|
|
807
|
+
`FieldStruct::Scaffold.from_json(sample)` writes the model class for a JSON sample (a JSON String or parsed data).
|
|
808
|
+
|
|
809
|
+
## Custom types
|
|
810
|
+
|
|
811
|
+
Subclass `FieldStruct::Types::Base`, implement `coerce(value, **options)` and `ruby_type`; optionally `missing?`,
|
|
812
|
+
`own_option_schema` (the options your type takes) and `rbs_type`. Raise `ArgumentError`, `TypeError` or `RangeError` from
|
|
813
|
+
`coerce` to mean "can't read this". Register it by name in a registry. A module that defines `field_types` returning
|
|
814
|
+
a registry makes the names available to every struct inside it, falling back to the built-in types.
|
|
815
|
+
|
|
816
|
+
```ruby run
|
|
817
|
+
require 'field_struct'
|
|
818
|
+
|
|
819
|
+
class Moisture < FieldStruct::Types::Base
|
|
820
|
+
def coerce(value, **)
|
|
821
|
+
return nil if value.nil?
|
|
822
|
+
|
|
823
|
+
number = Float(value.to_s.delete_suffix('%'))
|
|
824
|
+
raise ArgumentError, 'Moisture fields expect 0 to 100' unless (0..100).cover?(number)
|
|
825
|
+
|
|
826
|
+
number
|
|
827
|
+
end
|
|
828
|
+
|
|
829
|
+
def ruby_type = Float
|
|
830
|
+
def rbs_type = '::Float'
|
|
831
|
+
end
|
|
832
|
+
|
|
833
|
+
module Seedbank
|
|
679
834
|
def self.field_types
|
|
680
|
-
@field_types ||= FieldStruct.new_registry
|
|
681
|
-
register :money, Acme::Types::Money # add a type
|
|
682
|
-
register :dec, :big_decimal # alias to an existing name
|
|
683
|
-
end
|
|
835
|
+
@field_types ||= FieldStruct.new_registry { register :moisture, Moisture }
|
|
684
836
|
end
|
|
685
837
|
|
|
686
|
-
class
|
|
687
|
-
required :
|
|
838
|
+
class Lot < FieldStruct::Base
|
|
839
|
+
required :humidity, :moisture
|
|
688
840
|
end
|
|
689
841
|
end
|
|
842
|
+
|
|
843
|
+
Seedbank::Lot.new(humidity: '42%').humidity # => 42.0
|
|
844
|
+
Seedbank::Lot.new(humidity: '420%').valid? # => false
|
|
845
|
+
FieldStruct.types.key?(:moisture) # => false
|
|
690
846
|
```
|
|
691
847
|
|
|
692
|
-
|
|
693
|
-
|
|
848
|
+
`FieldStruct.new_registry(parent = FieldStruct.types, &block)` builds a registry; `register(:name, SomeClass)` adds a
|
|
849
|
+
type and `register(:alias, :existing)` aliases one. `registry.lookup(:moisture)` returns the class, and raises
|
|
850
|
+
`KeyError` for an unknown name; `registry.type_classes` lists every class it resolves, its own first.
|
|
694
851
|
|
|
695
|
-
|
|
696
|
-
`
|
|
852
|
+
A type's options are its `option_schema` (built from `own_option_schema`, inherited keys first). Two class-level hooks
|
|
853
|
+
run at declaration: `resolve_options(options, **)` returns the options to store (override it to
|
|
854
|
+
turn a preset Symbol into a value, or to reject a bad one), and `resolve_format(format)` returns a `format:` unchanged,
|
|
855
|
+
raising for a Symbol when the type has no presets:
|
|
697
856
|
|
|
698
|
-
|
|
857
|
+
```ruby run
|
|
858
|
+
require 'field_struct'
|
|
699
859
|
|
|
700
|
-
|
|
860
|
+
FieldStruct.types.lookup(:integer) # => FieldStruct::Types::Integer
|
|
861
|
+
FieldStruct::Types::Integer.option_schema.keys # => [:in, :base, :strict]
|
|
862
|
+
FieldStruct::Types::Base.resolve_format('%Y') # => "%Y"
|
|
863
|
+
```
|
|
864
|
+
|
|
865
|
+
## Exceptions
|
|
866
|
+
|
|
867
|
+
```
|
|
868
|
+
StandardError
|
|
869
|
+
FieldStruct::Error
|
|
870
|
+
FieldStruct::CoercionError #field_name, #original
|
|
871
|
+
FieldStruct::ImmutableError
|
|
872
|
+
FieldStruct::UnknownAttributeError #keys
|
|
873
|
+
```
|
|
701
874
|
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
User.metadata[:age] # => #<FieldStruct::Field :age Integer>
|
|
705
|
-
User.attribute_names # => [:name, :age]
|
|
706
|
-
field = User.metadata[:age]
|
|
707
|
-
field.name; field.type; field.required?; field.default; field.options; field.type_instance.ruby_type
|
|
708
|
-
```
|
|
709
|
-
|
|
710
|
-
---
|
|
711
|
-
|
|
712
|
-
## RBS for your own classes
|
|
713
|
-
|
|
714
|
-
Sord types the library; `FieldStruct::RBS.generate` types the accessors **your**
|
|
715
|
-
`field` declarations create, so Steep/Solargraph can check `order.items`:
|
|
716
|
-
|
|
717
|
-
```ruby
|
|
718
|
-
class Order < FieldStruct::Base
|
|
719
|
-
required :id, :uuid
|
|
720
|
-
optional :items, :array, of: LineItem
|
|
721
|
-
optional :status, :union, of: %i[symbol boolean]
|
|
722
|
-
optional :scope, :value, rbs_type: '::ActiveRecord::Relation'
|
|
723
|
-
optional :extra, :value
|
|
724
|
-
end
|
|
725
|
-
|
|
726
|
-
puts FieldStruct::RBS.generate(Order)
|
|
727
|
-
# # Generated by FieldStruct::RBS. Types describe a valid instance: an
|
|
728
|
-
# # invalid one (a required field left unset, or a :keep_raw coercion
|
|
729
|
-
# # failure holding the raw input) can hold other values. Check valid?.
|
|
730
|
-
# class Order < ::FieldStruct::Base
|
|
731
|
-
# attr_reader id: ::String
|
|
732
|
-
# def id=: (::String? value) -> ::String?
|
|
733
|
-
#
|
|
734
|
-
# attr_reader items: ::Array[::LineItem]?
|
|
735
|
-
# def items=: (::Array[::LineItem]? value) -> ::Array[::LineItem]?
|
|
736
|
-
#
|
|
737
|
-
# attr_reader status: (::Symbol | bool)?
|
|
738
|
-
# def status=: ((::Symbol | bool)? value) -> (::Symbol | bool)?
|
|
739
|
-
#
|
|
740
|
-
# attr_reader scope: ::ActiveRecord::Relation?
|
|
741
|
-
# def scope=: (::ActiveRecord::Relation? value) -> ::ActiveRecord::Relation?
|
|
742
|
-
#
|
|
743
|
-
# attr_reader extra: untyped
|
|
744
|
-
# def extra=: (untyped value) -> untyped
|
|
745
|
-
# end
|
|
746
|
-
```
|
|
747
|
-
|
|
748
|
-
- **Types describe a valid instance.** Reader = the field's Ruby type; nullability
|
|
749
|
-
follows `required?` (required → `T`, optional → `T?`). An invalid instance (unset
|
|
750
|
-
required field, `:keep_raw` failure holding raw input) can hold other values.
|
|
751
|
-
- **Writer** is `(T? value) -> T?` — the setter takes `nil` and returns the coerced
|
|
752
|
-
value. Loose input it would coerce (`user.age = "30"` on an `:integer` field) runs
|
|
753
|
-
fine but is a Steep error; coerce at the boundary.
|
|
754
|
-
- **Generics are filled in:** `::Array[::LineItem]` (a scalar element is nullable: `of: :string` → `::Array[::String?]`, because `["x", nil]` is valid), unions `(A | B)` (boolean →
|
|
755
|
-
`bool`), nested structs by qualified name. A custom type whose `ruby_type` is a bare
|
|
756
|
-
generic (`::Hash`) emits `::Hash[untyped, untyped]` unless the type defines
|
|
757
|
-
`rbs_type` (`def rbs_type = '::Hash[::Symbol, ::String]'`).
|
|
758
|
-
- **`:value`** (and a union with a `:value` member) is `untyped`, reader and writer.
|
|
759
|
-
- **`rbs_type:`** (field) beats the type's `rbs_type`, which beats the derived type.
|
|
760
|
-
It replaces `T` verbatim — `?` is still added for optional readers and all
|
|
761
|
-
writers, and a union override is parenthesized first. Must be a non-blank String
|
|
762
|
-
(checked at declaration; not parsed — `rbs` isn't a runtime dependency). Fully
|
|
763
|
-
qualify constants (`::ActiveRecord::Relation`).
|
|
764
|
-
|
|
765
|
-
`FieldStruct::RBS.type_for(field, nullable: nil)` returns one field's type exactly as
|
|
766
|
-
`generate` emits it, for generators that type methods taking or returning the field:
|
|
767
|
-
|
|
768
|
-
```ruby
|
|
769
|
-
FieldStruct::RBS.type_for(Order.metadata[:items]) # => "::Array[::LineItem]?"
|
|
770
|
-
FieldStruct::RBS.type_for(Order.metadata[:items], nullable: false) # => "::Array[::LineItem]"
|
|
771
|
-
FieldStruct::RBS.type_for(Order.metadata[:id], nullable: true) # => "::String?"
|
|
772
|
-
```
|
|
773
|
-
|
|
774
|
-
`nullable: nil` (default) follows `!field.required?`; `untyped` never gets `?`.
|
|
775
|
-
Generate RBS for nested/element classes too so `::LineItem` references resolve. See
|
|
776
|
-
the README "Type signatures" section for a Rake-task wiring example.
|
|
777
|
-
|
|
778
|
-
---
|
|
779
|
-
|
|
780
|
-
## Gotchas / invariants
|
|
781
|
-
|
|
782
|
-
- **Setters are permissive by design** — `user.age = "30"` is valid (coerces). The
|
|
783
|
-
generated writer is typed `(T? value) -> T?`, so Steep flags that line even though
|
|
784
|
-
Ruby accepts it.
|
|
785
|
-
- **A required field can still be `nil`** (coercion failed under `:keep_raw`/`:replace`,
|
|
786
|
-
or never assigned). Check `valid?`; don't assume required ⇒ non-nil.
|
|
787
|
-
- **Whitespace-only strings are "missing"** for `:string` and its subclasses
|
|
788
|
-
(`:uuid`/`:url`/`:email`/`:immutable_string`). `:binary` is the exception — its
|
|
789
|
-
whitespace bytes are real data, so only nil/empty count as missing.
|
|
790
|
-
- **`nil` passes through coercion as `nil`** for essentially every type.
|
|
791
|
-
- **Temporal coercion behaves the same with or without ActiveSupport loaded.**
|
|
792
|
-
That is a deliberate invariant, not a coincidence — see `.claude/project_intent.md`
|
|
793
|
-
invariant 8. Coercion dispatches on explicit stdlib classes rather than on
|
|
794
|
-
`respond_to?(:to_date)` and friends, which ActiveSupport defines on every String.
|
|
795
|
-
- `:array` requires `of:`; `:union` requires `of: [...]` with ≥2 members. Options for
|
|
796
|
-
each array element go in `element: { ... }`, not on the field.
|
|
797
|
-
- Option scoping: `format:` → string-shaped + date/time/datetime; `enum:` →
|
|
798
|
-
string/symbol; `in:` → integer/float/decimal/date/time/datetime; `round:` →
|
|
799
|
-
float/decimal; `base:` → integer; `strict:` → string-shaped/integer; `values:` → boolean; `element:` → array. Misapplying raises `ArgumentError` at declaration.
|
|
800
|
-
- `description:`/`desc:` is documentation only — absent from `attributes`, `as_json`,
|
|
801
|
-
and pattern-match keys.
|
|
802
|
-
- **Input is a Hash, or anything with `to_hash`** (e.g. a permitted
|
|
803
|
-
`ActionController::Parameters`). `new(nil)` is the same as `new`; any other
|
|
804
|
-
shape (`new([])`, `new("x")`, `assign_attributes(nil)`) raises `ArgumentError`
|
|
805
|
-
naming the class it got.
|
|
806
|
-
- **`dup` / `clone` copy the errors too** — the copy starts with the original's
|
|
807
|
-
messages but owns them, so changing one's top-level fields never changes the
|
|
808
|
-
other's `valid?`. The copy is shallow: nested structs are shared.
|
|
809
|
-
- **Some field names are reserved** — the ones `Base` calls on its own instances
|
|
810
|
-
(`errors`, `attributes`, `hash`, `class`, `send`, `to_h`, `inspect`, … — see
|
|
811
|
-
`FieldStruct::Base::RESERVED_FIELD_NAMES`). Declaring one raises `ArgumentError`
|
|
812
|
-
naming it; name the field something else and map the external key with
|
|
813
|
-
`serialize :json, errors_field: 'errors'`. `method`, `name`, `type` stay legal.
|
|
814
|
-
- Unknown input keys are dropped by default (`unknown_attributes :ignore`); set
|
|
815
|
-
`:raise` to reject them with `UnknownAttributeError` — recommended at payment/API
|
|
816
|
-
boundaries, on each struct (see [above](#payment-and-api-boundaries-unknown_attributes-raise)).
|
|
817
|
-
- **Validity is computed on assignment.** In-place mutation of a nested struct or an
|
|
818
|
-
array element doesn't refresh the parent's errors; re-assign the field (see
|
|
819
|
-
[staleness](#validity-is-computed-on-assignment-shallow-valid-staleness)).
|
|
820
|
-
- Uses **Oj** for JSON (`Oj.load`/`Oj.dump`), not the stdlib JSON.
|
|
875
|
+
`from_json` raises Ruby's `EncodingError` for malformed JSON and `ArgumentError` for a non-object root. Declaration
|
|
876
|
+
mistakes raise `ArgumentError` (or `KeyError` for an unknown type name) while the class body runs.
|