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/docs/getting_started.md
CHANGED
|
@@ -1,337 +1,151 @@
|
|
|
1
|
-
# Getting started
|
|
1
|
+
# Getting started
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
presence/format validation. Construction and validity are **separate** — you can
|
|
6
|
-
build an invalid instance and ask it `valid?`.
|
|
3
|
+
This page maps tasks to the API, explains what each error means and how to fix it, walks through one model end to
|
|
4
|
+
end, and lists the mistakes people make first. [USAGE.md](../USAGE.md) is the full reference.
|
|
7
5
|
|
|
8
|
-
|
|
9
|
-
options see [`USAGE.md`](../USAGE.md); for the feature tour see
|
|
10
|
-
[`README.md`](../README.md).
|
|
6
|
+
## What do you want to do?
|
|
11
7
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
| You want to… | Do this |
|
|
8
|
+
| Task | Use |
|
|
15
9
|
|---|---|
|
|
16
|
-
|
|
|
17
|
-
|
|
|
18
|
-
|
|
|
19
|
-
|
|
|
20
|
-
|
|
|
21
|
-
|
|
|
22
|
-
|
|
|
23
|
-
|
|
|
24
|
-
|
|
|
25
|
-
|
|
|
26
|
-
|
|
|
27
|
-
|
|
|
28
|
-
|
|
|
29
|
-
|
|
|
30
|
-
|
|
|
31
|
-
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
---
|
|
45
|
-
|
|
46
|
-
## Part 1 — Any Ruby project
|
|
47
|
-
|
|
48
|
-
### Your first model
|
|
49
|
-
|
|
50
|
-
<!-- doctest -->
|
|
51
|
-
```ruby
|
|
52
|
-
class User < FieldStruct::Base
|
|
53
|
-
required :name, :string
|
|
54
|
-
optional :age, :integer
|
|
55
|
-
end
|
|
56
|
-
|
|
57
|
-
u = User.new(name: 'Alice', age: '30') # Symbol or String keys both work
|
|
58
|
-
u.age # => 30
|
|
59
|
-
u.valid? # => true
|
|
60
|
-
u.attributes # => { name: "Alice", age: 30 }
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
`required` presence-checks the field; `optional` (and bare `field`) don't. The value
|
|
64
|
-
is coerced through the type — note `'30'` became `30`.
|
|
65
|
-
|
|
66
|
-
### Start fast from an existing payload
|
|
67
|
-
|
|
68
|
-
Modeling an external API or webhook? Don't hand-write the class — scaffold a starter
|
|
69
|
-
from a sample and refine it. It's a **prototype you finish**, not a finished model.
|
|
70
|
-
|
|
71
|
-
<!-- doctest -->
|
|
72
|
-
```ruby
|
|
73
|
-
src = FieldStruct::Scaffold.from_json('{"id": 1, "active": true, "ref": "00421"}')
|
|
74
|
-
src.include?('required :id, :integer') # => true
|
|
75
|
-
src.include?('required :active, :boolean') # => true
|
|
76
|
-
src.include?('required :ref, :string') # => true
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
It's conservative on purpose: real JSON booleans/numbers get typed; **strings stay
|
|
80
|
-
`:string`** (a numeric-looking `"00421"` must not silently become an Integer), with a
|
|
81
|
-
trailing `# …` comment nudging you. Objects become nested classes, arrays become
|
|
82
|
-
`:array, of: …`. Pass an **array of same-shape objects** to get more signal — empty
|
|
83
|
-
fields resolve from samples that have them, presence drives `required`/`optional`, and
|
|
84
|
-
small repeated vocabularies surface as `# values: [...] — enum?` hints.
|
|
85
|
-
|
|
86
|
-
Then you add the things no tool can infer: enums, `required`, `description:`, formats,
|
|
87
|
-
and final scalar types — the comments point at where.
|
|
88
|
-
|
|
89
|
-
### Where files go
|
|
90
|
-
|
|
91
|
-
One class per file; name the file after the class. In a plain Ruby project, put them
|
|
92
|
-
under `lib/` and `require` them (FieldStruct uses explicit requires, no autoloading):
|
|
93
|
-
|
|
94
|
-
```
|
|
95
|
-
lib/
|
|
96
|
-
payments/
|
|
97
|
-
webhook_payload.rb # class Payments::WebhookPayload < FieldStruct::Base
|
|
98
|
-
line_item.rb # class Payments::LineItem < FieldStruct::Base
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
Declare a nested/element class **before** the class that references it.
|
|
102
|
-
|
|
103
|
-
### Reading and writing JSON
|
|
104
|
-
|
|
105
|
-
`serialize :json` maps internal field names to external keys; `from_json` reverse-maps
|
|
106
|
-
on the way in, `as_json`/`to_json` forward-map on the way out.
|
|
107
|
-
|
|
108
|
-
<!-- doctest -->
|
|
109
|
-
```ruby
|
|
110
|
-
class Charge < FieldStruct::Base
|
|
111
|
-
required :amount, :integer
|
|
112
|
-
optional :note, :string
|
|
113
|
-
serialize :json, amount: 'amountCents' # declare fields first, then serialize
|
|
114
|
-
end
|
|
115
|
-
|
|
116
|
-
c = Charge.from_json('{"amountCents": 500}')
|
|
117
|
-
c.amount # => 500
|
|
118
|
-
c.valid? # => true
|
|
119
|
-
c.to_json # => '{"amountCents":500,"note":null}'
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
Everything round-trips except `:value` (no type info to restore). JSON is handled with
|
|
123
|
-
Oj.
|
|
124
|
-
|
|
125
|
-
### A complete example — nesting, arrays, coercion
|
|
126
|
-
|
|
127
|
-
<!-- doctest -->
|
|
128
|
-
```ruby
|
|
129
|
-
class LineItem < FieldStruct::Base
|
|
130
|
-
required :sku, :string
|
|
131
|
-
required :qty, :integer
|
|
132
|
-
end
|
|
133
|
-
|
|
134
|
-
class Order < FieldStruct::Base
|
|
135
|
-
required :id, :string
|
|
136
|
-
required :items, :array, of: LineItem
|
|
137
|
-
end
|
|
138
|
-
|
|
139
|
-
order = Order.from_json('{"id":"A1","items":[{"sku":"X","qty":"2"}]}')
|
|
140
|
-
order.id # => "A1"
|
|
141
|
-
order.items.first.qty # => 2 (coerced from "2")
|
|
142
|
-
order.valid? # => true
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
Nested structs and arrays-of-structs coerce and validate recursively — an `Order` with
|
|
146
|
-
an invalid `LineItem` is itself invalid.
|
|
147
|
-
|
|
148
|
-
### Introspecting a model
|
|
149
|
-
|
|
150
|
-
`Klass.metadata.to_h` is a copy-pasteable view of a model's shape — handy for *seeing*
|
|
151
|
-
a class without opening its source.
|
|
152
|
-
|
|
153
|
-
<!-- doctest -->
|
|
154
|
-
```ruby
|
|
155
|
-
class Widget < FieldStruct::Base
|
|
156
|
-
required :name, :string
|
|
157
|
-
optional :size, :integer
|
|
158
|
-
end
|
|
159
|
-
|
|
160
|
-
Widget.metadata.to_h[:name][:type] # => "String"
|
|
161
|
-
Widget.metadata.to_h[:size][:required] # => false
|
|
162
|
-
```
|
|
163
|
-
|
|
164
|
-
### When things are invalid — errors
|
|
165
|
-
|
|
166
|
-
A FieldStruct always constructs; check `valid?` and read `errors`.
|
|
167
|
-
|
|
168
|
-
<!-- doctest -->
|
|
169
|
-
```ruby
|
|
170
|
-
class Account < FieldStruct::Base
|
|
171
|
-
required :email, :string
|
|
172
|
-
end
|
|
173
|
-
|
|
174
|
-
a = Account.new(email: ' ') # whitespace-only counts as missing
|
|
175
|
-
a.valid? # => false
|
|
176
|
-
a.errors[:email] # => ["is required"]
|
|
177
|
-
```
|
|
178
|
-
|
|
179
|
-
What the messages mean and what to do:
|
|
180
|
-
|
|
181
|
-
| You see | It means | Do |
|
|
10
|
+
| Define a model | `class Plant < FieldStruct::Base` with `required` / `optional` / `field` |
|
|
11
|
+
| Read untrusted input (a form, a hash) | `Plant.new(params)`, then `valid?` and `errors` |
|
|
12
|
+
| Read JSON | `Plant.from_json(string)` |
|
|
13
|
+
| Write JSON | `plant.to_json`, or `plant.as_json` for a Hash |
|
|
14
|
+
| Rename keys in JSON | `serialize :json, leaves: 'leafCount'` |
|
|
15
|
+
| Make it raise instead of recording | `coercion_policy :raise`, `unknown_attributes :raise` |
|
|
16
|
+
| Make it read-only | `immutable!` (setters raise) or `frozen!` (instances frozen) |
|
|
17
|
+
| "Change" a read-only object | `plant.with(leaves: 300)` returns a copy |
|
|
18
|
+
| Check two fields against each other | `validate :method` (add to `errors[:base]`) |
|
|
19
|
+
| Limit values | `in:` (numbers, dates), `enum:` (strings, symbols), `format:` (strings) |
|
|
20
|
+
| Nest one model in another | `optional :author, Botanist` |
|
|
21
|
+
| A list of things | `optional :tags, :array, of: :string` |
|
|
22
|
+
| A map from names to values | `optional :stock, :hash, of: :integer` (keys become Strings) |
|
|
23
|
+
| One of several types | `optional :tag, :union, of: %i[integer uuid]` |
|
|
24
|
+
| Take a PATCH body | `Plant.partial.new(params)`, then `given_fields`; the partial has `json_omit :unset`, so `as_json` writes only what was sent |
|
|
25
|
+
| Read another object (a record, a Struct) into a model | `mirror!` on the model, then pass the object to a field of that type |
|
|
26
|
+
| Keep a secret out of logs | `sensitive: true` |
|
|
27
|
+
| Add your own type | subclass `FieldStruct::Types::Base`, register it in a registry |
|
|
28
|
+
| See what a model accepts | `Plant.describe`, `Plant.metadata.to_h` |
|
|
29
|
+
| Get RBS for a model | `FieldStruct::RBS.generate(Plant)` |
|
|
30
|
+
| Get a model from sample JSON | `FieldStruct::Scaffold.from_json(sample)` |
|
|
31
|
+
|
|
32
|
+
## What an error means
|
|
33
|
+
|
|
34
|
+
`obj.errors.to_h` maps field names to messages. Messages never contain the value, only its class.
|
|
35
|
+
|
|
36
|
+
| Message | Meaning | Fix |
|
|
182
37
|
|---|---|---|
|
|
183
|
-
| `
|
|
184
|
-
| `
|
|
185
|
-
| `
|
|
186
|
-
| `
|
|
187
|
-
| `
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
```ruby
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
end
|
|
218
|
-
end
|
|
219
|
-
```
|
|
220
|
-
|
|
221
|
-
### Agent toolbox
|
|
222
|
-
|
|
223
|
-
If you're an AI assistant working in this repo, reach for the gem's machine
|
|
224
|
-
affordances instead of guessing:
|
|
225
|
-
|
|
226
|
-
- `pp Klass.metadata.to_h` — *see* a model's fields/types without reading its source.
|
|
227
|
-
- `FieldStruct::Scaffold.from_json(json)` — bootstrap a model from a sample payload.
|
|
228
|
-
- `FieldStruct::RBS.generate(Klass)` — emit RBS for a model's accessors (Steep/Solargraph).
|
|
229
|
-
- The gem ships [`USAGE.md`](../USAGE.md) (full reference) and a Claude Code skill
|
|
230
|
-
(`skills/field-struct/SKILL.md`) — both are in `bundle show field_struct`.
|
|
231
|
-
|
|
232
|
-
---
|
|
233
|
-
|
|
234
|
-
## Part 2 — Rails
|
|
235
|
-
|
|
236
|
-
### Where FieldStruct fits (and doesn't)
|
|
237
|
-
|
|
238
|
-
Use it for **API/webhook payloads**, service-object inputs/outputs, typed config, and
|
|
239
|
-
value objects. It is **not** a form object and **not** an ActiveRecord model — it
|
|
240
|
-
doesn't persist or query. Its ActiveModel-shaped surface (`valid?`, `errors`,
|
|
241
|
-
`model_name`, `to_model`) means error rendering and `*_path` helpers work, but treat it
|
|
242
|
-
as a typed value object, not a form backer.
|
|
243
|
-
|
|
244
|
-
### File placement (Zeitwerk)
|
|
245
|
-
|
|
246
|
-
Put your structs in an autoloaded path so Rails loads them by name. A common choice is
|
|
247
|
-
`app/structs/`:
|
|
248
|
-
|
|
249
|
-
```
|
|
250
|
-
app/structs/
|
|
251
|
-
payments/
|
|
252
|
-
webhook_payload.rb # class Payments::WebhookPayload < FieldStruct::Base
|
|
253
|
-
line_item.rb # class Payments::LineItem < FieldStruct::Base
|
|
254
|
-
```
|
|
255
|
-
|
|
256
|
-
The path mirrors the constant: `app/structs/payments/line_item.rb` ↔
|
|
257
|
-
`Payments::LineItem`. Zeitwerk autoloads them — no `require` needed in app code. (If you
|
|
258
|
-
reference structs at boot, rely on eager loading in production.)
|
|
259
|
-
|
|
260
|
-
### Inbound — parsing a webhook or API request
|
|
261
|
-
|
|
262
|
-
```ruby
|
|
263
|
-
class WebhooksController < ApplicationController
|
|
264
|
-
def nmi
|
|
265
|
-
payload = Payments::WebhookPayload.from_json(request.raw_post)
|
|
266
|
-
|
|
267
|
-
if payload.valid?
|
|
268
|
-
ProcessTransaction.call(payload)
|
|
269
|
-
head :ok
|
|
270
|
-
else
|
|
271
|
-
Rails.logger.warn(payload.errors.to_h)
|
|
272
|
-
head :unprocessable_entity
|
|
273
|
-
end
|
|
274
|
-
end
|
|
275
|
-
end
|
|
276
|
-
```
|
|
277
|
-
|
|
278
|
-
`from_json` applies any `serialize :json` mapping, so a `firstName` JSON key lands in a
|
|
279
|
-
`first_name` field. Build the struct, check `valid?`, branch.
|
|
280
|
-
|
|
281
|
-
### Outbound — rendering JSON
|
|
282
|
-
|
|
283
|
-
```ruby
|
|
284
|
-
def show
|
|
285
|
-
charge = build_charge
|
|
286
|
-
render json: charge # uses as_json/to_json, applying the :json mapping
|
|
38
|
+
| `is required` | the field is nil, blank (strings), or empty (arrays and hashes) | send a value, or declare it `optional` |
|
|
39
|
+
| `is invalid` | the value was read fine but broke `format:`, `enum:` or `in:`, or a nested struct inside it is invalid | send an allowed value; for a nested struct, look at its own `errors` |
|
|
40
|
+
| `could not be coerced: ...` | the type could not read the value (the text after the colon says why) | send something the type can read; see the type's row in USAGE |
|
|
41
|
+
| `is too long (maximum is 4)`, `is too short (minimum is 2)` | a string broke `length:` | send a value of that length |
|
|
42
|
+
| `element at index 2 is invalid` | an array element broke the `element:` options | fix those elements |
|
|
43
|
+
| `could not be coerced: element at index 1: ...` | an array element could not be read | fix that element |
|
|
44
|
+
| `1 entry is invalid`, `2 entries are invalid` | values of a `:hash` broke the `element:` options | fix those values |
|
|
45
|
+
| `has too many items (maximum is 3)` | an array is longer than its `max_items:` | send fewer |
|
|
46
|
+
|
|
47
|
+
Raised errors, when a policy asks for them or a declaration or call can't go on:
|
|
48
|
+
|
|
49
|
+
| Exception | When | Look at |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| `FieldStruct::CoercionError` | `coercion_policy :raise` and a value could not be read | `field_name`, `original` |
|
|
52
|
+
| `FieldStruct::UnknownAttributeError` | `unknown_attributes :raise` and a key matched no field | `keys` |
|
|
53
|
+
| `FieldStruct::ImmutableError` | a setter was called on an `immutable!` object | use `with` |
|
|
54
|
+
| `KeyError` at class definition | an unknown type name (`no FieldStruct type registered for :strng (did you mean :string?)`) | the suggested name, or register the type |
|
|
55
|
+
| `ArgumentError` at class definition | a bad declaration (bad option, reserved name) | the message names the field and the fix |
|
|
56
|
+
| `ArgumentError` at class definition | an unknown option key (`unknown option defualt: on field :slot (did you mean default:?)`), or an adapter key like `avro:` before its `require` | the suggested key, or require the adapter first |
|
|
57
|
+
| `ArgumentError` from `register_option` | the key is built in, or already registered with another `type:` or `owner:` | pick another key |
|
|
58
|
+
| `ArgumentError` from `partial` | the class already defines its own `Partial` constant | rename that constant |
|
|
59
|
+
| `ArgumentError` when a mirror reads an object | the object lacks a public reader for a field (`LampView mirrors Bulb, but Bulb has no public reader for :watts`) | add the reader, or build from a Hash |
|
|
60
|
+
| `ArgumentError` when a mirror reads a lazy collection | an array of mirrors has no `max_items:` (`set max_items: on Hall#lamps, or load the relation yourself`) | set `max_items:`, or pass an Array |
|
|
61
|
+
| `EncodingError` from `from_json` | malformed JSON | check the source |
|
|
62
|
+
| `ArgumentError` from `from_json` | the JSON root isn't an object | send an object |
|
|
63
|
+
|
|
64
|
+
## One model, start to finish
|
|
65
|
+
|
|
66
|
+
```ruby run
|
|
67
|
+
require 'field_struct'
|
|
68
|
+
|
|
69
|
+
class Botanist < FieldStruct::Base
|
|
70
|
+
required :name, :string
|
|
71
|
+
optional :born, :date, format: :iso8601
|
|
287
72
|
end
|
|
288
|
-
```
|
|
289
|
-
|
|
290
|
-
### Scaffolding a model for a new integration
|
|
291
|
-
|
|
292
|
-
The fastest way to onboard a new provider:
|
|
293
|
-
|
|
294
|
-
1. Capture a sample payload (or several) into `spec/fixtures/` (or a console).
|
|
295
|
-
2. Generate a starter class and drop it into `app/structs/`:
|
|
296
|
-
|
|
297
|
-
```ruby
|
|
298
|
-
# rails runner / console
|
|
299
|
-
src = FieldStruct::Scaffold.from_json(File.read('spec/fixtures/nmi_sale.json'),
|
|
300
|
-
class_name: 'Payments::NmiSale')
|
|
301
|
-
File.write('app/structs/payments/nmi_sale.rb', src)
|
|
302
|
-
```
|
|
303
73
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
74
|
+
class Plant < FieldStruct::Base
|
|
75
|
+
required :species, :string
|
|
76
|
+
required :accession, :string, format: /\AACC-\d{5}\z/
|
|
77
|
+
optional :leaves, :integer, in: 1..5000
|
|
78
|
+
optional :yield_kg, :decimal, round: 2
|
|
79
|
+
optional :author, Botanist
|
|
80
|
+
optional :tags, :array, of: :string
|
|
81
|
+
optional :kind, :symbol, enum: %i[shrub climber], default: :shrub
|
|
82
|
+
serialize :json, accession: 'TAG'
|
|
308
83
|
|
|
309
|
-
|
|
310
|
-
required/optional and enum inference.
|
|
84
|
+
validate :heavy_plants_need_a_yield
|
|
311
85
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
If your app runs a type checker, generate RBS for your structs' accessors (the dynamic
|
|
315
|
-
`field` methods Sord can't see):
|
|
316
|
-
|
|
317
|
-
```ruby
|
|
318
|
-
# lib/tasks/field_struct_rbs.rake
|
|
319
|
-
namespace :field_struct do
|
|
320
|
-
task rbs: :environment do
|
|
321
|
-
classes = [Payments::WebhookPayload, Payments::LineItem]
|
|
322
|
-
File.write('sig/field_structs.rbs',
|
|
323
|
-
classes.map { |k| FieldStruct::RBS.generate(k) }.join("\n"))
|
|
86
|
+
def heavy_plants_need_a_yield
|
|
87
|
+
errors.add(:base, 'Plants over 1000 leaves need a yield_kg') if leaves && leaves > 1000 && yield_kg.nil?
|
|
324
88
|
end
|
|
325
89
|
end
|
|
326
|
-
```
|
|
327
|
-
|
|
328
|
-
Generate RBS for nested/element classes too, so references like `::Payments::LineItem`
|
|
329
|
-
resolve.
|
|
330
|
-
|
|
331
|
-
---
|
|
332
|
-
|
|
333
|
-
## Where to go next
|
|
334
90
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
91
|
+
# 1. Build from untrusted input and look at the result.
|
|
92
|
+
plant = Plant.new(species: 'Monstera', accession: 'ACC-20931', leaves: '412', yield_kg: '9.999',
|
|
93
|
+
author: {name: 'Maria Merian', born: '1647-04-02'})
|
|
94
|
+
plant.valid? # => true
|
|
95
|
+
plant.yield_kg.to_s('F') # => "10.0"
|
|
96
|
+
plant.author.born.year # => 1647
|
|
97
|
+
|
|
98
|
+
# 2. Bad input is kept, flagged, and explained.
|
|
99
|
+
bad = Plant.new(species: '', accession: '123', leaves: 2000)
|
|
100
|
+
bad.errors.to_h.keys # => [:species, :accession, :base]
|
|
101
|
+
bad.errors.full_messages.last # => "Plants over 1000 leaves need a yield_kg"
|
|
102
|
+
|
|
103
|
+
# 3. JSON uses the mapped names, both ways.
|
|
104
|
+
json = plant.to_json
|
|
105
|
+
json.include?('"TAG":"ACC-20931"') # => true
|
|
106
|
+
Plant.from_json(json) == plant # => true
|
|
107
|
+
|
|
108
|
+
# 4. Describe it.
|
|
109
|
+
puts Plant.describe.lines.first
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Mistakes people make first
|
|
113
|
+
|
|
114
|
+
1. **Expecting setters to raise.** They don't. `plant.leaves = 'many'` stores `'many'` and adds an error. Check `valid?`,
|
|
115
|
+
or set `coercion_policy :raise` on the class.
|
|
116
|
+
2. **Reading "required" as "never nil".** Required means `valid?` fails when the value is missing. A fresh object with a
|
|
117
|
+
required field unset is allowed to exist; its reader returns `nil`. Whitespace-only strings, empty arrays and empty hashes
|
|
118
|
+
count as missing.
|
|
119
|
+
3. **Forgetting `of:`.** `:array`, `:hash` and `:union` need it, and the declaration raises without it.
|
|
120
|
+
4. **Putting options on the wrong type.** `round:` belongs to numbers, `format:` to strings and dates, `enum:` to strings
|
|
121
|
+
and symbols. The error lists where the option does apply. Options for an element go in `element: {...}`, not on the
|
|
122
|
+
field.
|
|
123
|
+
5. **Putting cross-field rules in a field.** Use `validate` and add to `errors[:base]`.
|
|
124
|
+
6. **Using the standard library JSON.** `to_json` and `from_json` go through Oj. Call them; don't `JSON.generate` the
|
|
125
|
+
object.
|
|
126
|
+
7. **Ignoring unknown keys.** By default extra input keys are dropped without a word. Use `unknown_attributes :raise`
|
|
127
|
+
if a typo should fail loudly.
|
|
128
|
+
8. **Logging values and expecting masks.** Messages never echo values, but `inspect` does show them unless the field is
|
|
129
|
+
`sensitive: true`.
|
|
130
|
+
9. **Reading stale validity.** Validity is computed when you assign. Changing a nested object or an array element in
|
|
131
|
+
place doesn't refresh the parent. Re-assign it, or use `with`.
|
|
132
|
+
10. **Passing a Hash to `with`.** It takes keywords: `plant.with(**changes)`, not `plant.with(changes)`.
|
|
133
|
+
|
|
134
|
+
## Rails
|
|
135
|
+
|
|
136
|
+
field_struct doesn't need Rails and never requires ActiveSupport. It behaves the same with ActiveSupport loaded. Some
|
|
137
|
+
specifics:
|
|
138
|
+
|
|
139
|
+
- **Params.** Pass permitted parameters straight in: `Plant.new(params.require(:plant).permit(:species, :leaves))`. Anything
|
|
140
|
+
that responds to `to_hash` works, with String or Symbol keys. Pass `unknown_attributes :raise` to the class if you'd
|
|
141
|
+
rather fail on extra keys than drop them.
|
|
142
|
+
- **Naming.** `Plant.model_name` and `plant.to_model` exist, so form builders and URL helpers can name the class.
|
|
143
|
+
`form_with model: plant, url: '/plants'` nests the fields under `model_name.param_key` (`plant[species]`). Always pass
|
|
144
|
+
`url:`, since a struct has no routes. A struct is not an Active Model object: it has no persistence methods and no
|
|
145
|
+
`ActiveModel::Validations`. `valid?` and `errors` are field_struct's own; `errors.full_messages` returns Strings.
|
|
146
|
+
- **JSON.** `render json: plant` works: `as_json` ignores Rails' options and returns every field, except under
|
|
147
|
+
`json_omit :unset`, which leaves out a `nil` field the caller didn't send.
|
|
148
|
+
- **Time zones.** `zone:` takes IANA names (`America/Denver`), `UTC` or an offset, not Rails names like
|
|
149
|
+
`"Mountain Time (US & Canada)"`. Give it `ActiveSupport::TimeZone::MAPPING['Mountain Time (US & Canada)']` if you hold a
|
|
150
|
+
Rails name. Values come back as plain `Time` or `DateTime`, not `TimeWithZone`.
|
|
151
|
+
- **Load order.** Require ActiveSupport before or after the gem; nothing in field_struct depends on what it redefines.
|