minitwin 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f0d2a4f4cc32ed09cb11728a1f8b81edf576da9cfe341a3cf287a42d37d1adf5
4
- data.tar.gz: 23ea54c1c77af14a3782a70e617e4bc4fbbf206cc5f72df45de5ca67c7e0939c
3
+ metadata.gz: a88b3b0c0621f46a12f29babb5b44ea5743d2b401ba438ce676fc07588927d7b
4
+ data.tar.gz: 6919539f9a313ccb65c2eb2038c904298e51a0f00f86e1aee9283dbd592ace33
5
5
  SHA512:
6
- metadata.gz: a6f55c0a7e9b703b6451174d71f9835d3436728cad385a592133f385699a57fb26389255c073a5d4d043e970439d98f69126cc87b989a392a9586eb8689efcf6
7
- data.tar.gz: 72b755ef287bccb6eff9e7f3d9d8e3b32457cedf24f02bd1f93bab5679a7f1358d7dbdf1577011c41dd567bb820f7e67fba78e7b4f0d3ff460e8481ce8120bec
6
+ metadata.gz: 664bb2afc72af8f568f30600570345b9cc2b1c8d1c819cbb35c21341fe2652a97b702f2f9ff87dbd10d78178aa961b3b554b18a7b1923a2c038764aa0065bebe
7
+ data.tar.gz: a616365de759a97b7eae4851d7c68e4d95aaced564a26ca916fb21066f707cc3fced7bfd7bc874e915ea0fa034263ba5f3e0dabb8c534bd5529e255e893e93a3
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Minitwin
2
2
 
3
- ![Minitwin Logo](logo.png){width=20%}
3
+ <img src="logo.png" alt="Minitwin Logo" width="20%">
4
4
 
5
5
  ## What is Minitwin?
6
6
 
@@ -34,7 +34,7 @@ class UserTwin < Minitwin
34
34
  property :active, type: Types::Params::Bool.lax
35
35
  end
36
36
 
37
- user = UserTwin.from_hash(
37
+ user = UserTwin.new(
38
38
  id: "42",
39
39
  name: "Alex",
40
40
  active: "1"
@@ -91,7 +91,7 @@ MINITWIN_RBS_DIR=sig/custom_path rake minitwin:generate_rbs
91
91
 
92
92
  ## Inspiration
93
93
 
94
- Minitwin was inspired by [Disposable](https://github.com/apotonick/disposable), a gem for building twin objects as a decorator layer on top of your domain models.
94
+ Minitwin was inspired by [Disposable](https://github.com/apotonick/disposable).
95
95
 
96
96
 
97
97
  ## License
data/USAGE.md CHANGED
@@ -9,12 +9,14 @@
9
9
  - [Validations](#validations)
10
10
  - [Working with objects](#working-with-objects)
11
11
  - [Composition](#composition)
12
+ - [Round-tripping](#round-tripping)
13
+ - [Error Handling](#error-handling)
12
14
  - [DSL Reference](#dsl-reference)
13
15
  - [Public Interface](#public-interface)
14
16
 
15
17
  ## Basic
16
18
 
17
- Define properties and instantiate a twin from a hash:
19
+ Define properties and instantiate a twin, which can be serialized:
18
20
 
19
21
  ```ruby
20
22
  class ArticleTwin < Minitwin
@@ -22,7 +24,7 @@ class ArticleTwin < Minitwin
22
24
  property :published
23
25
  end
24
26
 
25
- article = ArticleTwin.from_hash(title: "Hello", published: true)
27
+ article = ArticleTwin.new(title: "Hello", published: true)
26
28
  article.title #=> "Hello"
27
29
  article.published #=> true
28
30
 
@@ -30,6 +32,17 @@ article.to_hash #=> { title: "Hello", published: true }
30
32
  article.to_json #=> '{"title":"Hello","published":true}'
31
33
  ```
32
34
 
35
+ It's also possible to instantiate a twin from a plain Ruby Hash or JSON string:
36
+
37
+ ```ruby
38
+ article = ArticleTwin.from_hash({title: "Hello", published: true})
39
+ article.title #=> "Hello"
40
+
41
+ json_string = { title: "Hello", published: true }.to_json
42
+ article = ArticleTwin.from_json(json_string)
43
+ article.title #=> "Hello"
44
+ ```
45
+
33
46
  ## Block properties
34
47
 
35
48
  A block creates an anonymous nested twin class for the property:
@@ -43,7 +56,7 @@ class PostTwin < Minitwin
43
56
  end
44
57
  end
45
58
 
46
- post = PostTwin.from_hash(title: "Hi", author: { name: "Ana", email: "ana@example.com" })
59
+ post = PostTwin.new(title: "Hi", author: { name: "Ana", email: "ana@example.com" })
47
60
  post.author.name #=> "Ana"
48
61
  post.to_hash #=> { title: "Hi", author: { name: "Ana", email: "ana@example.com" } }
49
62
  ```
@@ -60,10 +73,13 @@ class UserTwin < Minitwin
60
73
  property :address, twin: AddressTwin
61
74
  end
62
75
 
63
- user = UserTwin.from_hash(name: "Bob", address: { city: "Berlin" })
76
+ user = UserTwin.new(name: "Bob", address: { city: "Berlin" })
64
77
  user.address.city #=> "Berlin"
65
78
  ```
66
79
 
80
+ To lift a value out of a nested twin into a top-level property, see
81
+ [Flattening a nested twin](#flattening-a-nested-twin).
82
+
67
83
  ## Collection properties
68
84
 
69
85
  `collection` defines an array property. Each element can be a plain value or a nested twin:
@@ -73,7 +89,7 @@ class InvoiceTwin < Minitwin
73
89
  collection :tags
74
90
  end
75
91
 
76
- inv = InvoiceTwin.from_hash(tags: %w[urgent vip])
92
+ inv = InvoiceTwin.new(tags: %w[urgent vip])
77
93
  inv.tags #=> ["urgent", "vip"]
78
94
  ```
79
95
 
@@ -87,7 +103,7 @@ class OrderTwin < Minitwin
87
103
  end
88
104
  end
89
105
 
90
- order = OrderTwin.from_hash(lines: [
106
+ order = OrderTwin.new(lines: [
91
107
  { product: "Mug", qty: 2 },
92
108
  { product: "Shirt", qty: 1 }
93
109
  ])
@@ -109,7 +125,7 @@ class ProfileTwin < Minitwin
109
125
  end
110
126
  end
111
127
 
112
- t = ProfileTwin.from_hash(username: "dana", theme: "dark", locale: "en")
128
+ t = ProfileTwin.new(username: "dana", theme: "dark", locale: "en")
113
129
  t.theme #=> "dark"
114
130
  t.to_hash #=> { username: "dana", settings: { theme: "dark", locale: "en" } }
115
131
  ```
@@ -134,7 +150,7 @@ class TokenTwin < Minitwin
134
150
  property :internal_token, as: :token
135
151
  end
136
152
 
137
- t = TokenTwin.from_hash(internal_token: "abc")
153
+ t = TokenTwin.new(internal_token: "abc")
138
154
  t.token #=> "abc"
139
155
  t.to_hash #=> { token: "abc" }
140
156
  ```
@@ -147,7 +163,7 @@ class FieldTwin < Minitwin
147
163
  property :value, as: -> { key }
148
164
  end
149
165
 
150
- t = FieldTwin.from_hash(key: "score", value: 42)
166
+ t = FieldTwin.new(key: "score", value: 42)
151
167
  t.score #=> 42
152
168
  t.to_hash #=> { key: "score", score: 42 }
153
169
 
@@ -169,7 +185,7 @@ class EventTwin < Minitwin
169
185
  property :active, type: Types::Params::Bool.lax
170
186
  end
171
187
 
172
- ev = EventTwin.from_hash(visitor_count: "42", active: "1")
188
+ ev = EventTwin.new(visitor_count: "42", active: "1")
173
189
  ev.visitor_count #=> 42
174
190
  ev.active #=> true
175
191
  ```
@@ -184,7 +200,7 @@ class ContactTwin < Minitwin
184
200
  property :name, validates: { presence: true }
185
201
  end
186
202
 
187
- c = ContactTwin.from_hash(email: "", name: "")
203
+ c = ContactTwin.new(email: "", name: "")
188
204
  c.valid? #=> false
189
205
  c.errors.full_messages
190
206
  #=> ["Email can't be blank", "Email is invalid", "Name can't be blank"]
@@ -199,7 +215,7 @@ class RegistrationTwin < Minitwin
199
215
  end
200
216
  end
201
217
 
202
- r = RegistrationTwin.from_hash(contact: { email: "" })
218
+ r = RegistrationTwin.new(contact: { email: "" })
203
219
  r.valid? #=> false
204
220
  r.errors.full_messages #=> ["contact.email can't be blank"]
205
221
  ```
@@ -222,7 +238,7 @@ user.name #=> "Alex"
222
238
  `assign_hash` updates an existing twin in place (only known attributes):
223
239
 
224
240
  ```ruby
225
- twin = UserTwin.from_hash(name: "Alex", email: "old@example.com")
241
+ twin = UserTwin.new(name: "Alex", email: "old@example.com")
226
242
  twin.assign_hash(email: "new@example.com")
227
243
  twin.email #=> "new@example.com"
228
244
  ```
@@ -275,10 +291,203 @@ summary.id #=> 7
275
291
  summary.name #=> "Dana"
276
292
  ```
277
293
 
294
+ ### Flattening a nested twin
295
+
296
+ Use `on:` to read a property from a nested twin instead of a `from_objects` source: a symbol falls
297
+ back to a reader on the twin itself, and a lambda runs in instance context and returns any object
298
+ reachable from it. The nested structure is flattened into top-level properties:
299
+
300
+ ```ruby
301
+ class SiteTwin < Minitwin
302
+ property :address, expose: false do
303
+ property :city
304
+ property :installation do
305
+ property :street
306
+ end
307
+ end
308
+
309
+ property :city, on: :address # one level: a symbol is enough
310
+ property :street, on: -> { address.installation } # deeper path: use a lambda
311
+ end
312
+
313
+ site = SiteTwin.new(
314
+ address: { city: "Berlin", installation: { street: "1234 fake street" } }
315
+ )
316
+ site.city #=> "Berlin"
317
+ site.street #=> "1234 fake street"
318
+ site.to_hash #=> { city: "Berlin", street: "1234 fake street" }
319
+ ```
320
+
321
+ The property name is the reader called on the source: `city` is read as `address.city`. When the names
322
+ differ, or when a link in the path may be `nil`, use `getter:` instead — `property :town, getter: -> { address.city }`
323
+ or `getter: -> { address&.installation&.street }`.
324
+
325
+ The flattening only works for reading: `site.city = "Hamburg"` is discarded, so assign to
326
+ `site.address.city` instead.
327
+
328
+ ## Round-tripping
329
+
330
+ Talking to an API usually means two conversions: your own model has to become a request
331
+ payload, and the response has to become your own model again. Use **one twin per
332
+ direction** — a request twin that serializes, and a response twin that deserializes.
333
+
334
+ The request twin is written from your side: the property names are your model's attribute
335
+ names (so `from_object` can read them), and `as:` supplies the names the API expects:
336
+
337
+ ```ruby
338
+ class SubscriptionRequestTwin < Minitwin
339
+ property :plan
340
+ property :seats, as: :seat_count, type: Types::Params::Integer.lax
341
+ property :start_date, as: :activation_date, type: Types::Params::Date.lax
342
+ end
343
+
344
+ subscription = Subscription.new(plan: "pro", seats: "3", start_date: "2026-01-01")
345
+
346
+ request = SubscriptionRequestTwin.from_object(subscription)
347
+ request.to_json
348
+ #=> '{"plan":"pro","seat_count":3,"activation_date":"2026-01-01"}'
349
+ ```
350
+
351
+ The response twin is written from the API's side: the property names are the keys the API
352
+ sends (so `from_json`/`from_hash` can pick them up), and `as:` maps them back onto your own
353
+ vocabulary — which is also the name `sync` writes to on the model:
354
+
355
+ ```ruby
356
+ class SubscriptionResponseTwin < Minitwin
357
+ property :id, as: :remote_id
358
+ property :status
359
+ property :seat_count, as: :seats, type: Types::Params::Integer.lax
360
+ property :activation_date, as: :start_date, type: Types::Params::Date.lax
361
+ end
362
+
363
+ response = SubscriptionResponseTwin.from_json(api_response_body)
364
+ response.remote_id #=> "sub_1"
365
+ response.seats #=> 5
366
+ response.start_date #=> #<Date: 2026-02-01>
367
+
368
+ response.sync(subscription)
369
+ subscription.remote_id #=> "sub_1"
370
+ subscription.seats #=> 5
371
+ subscription.start_date #=> #<Date: 2026-02-01>
372
+ ```
373
+
374
+ Both twins declare the same mapping, just from opposite ends. Coercion happens on both
375
+ legs, so the payload carries a real `Integer` and the model receives a real `Date` — even
376
+ though the wire format is a string in both cases.
377
+
378
+ ### Why two twins and not one?
379
+
380
+ Reusing a single twin for both legs looks tempting: the mapping is the same, so why declare
381
+ it twice? Because a twin is a *directed* mapping, not a bidirectional schema. Its structure
382
+ is already asymmetric:
383
+
384
+ - **Input keys** are the property names (the generated setters), so a hash is read using the
385
+ original names.
386
+ - **Output keys** follow `as:`, and `as:` also protects the original name — so what
387
+ `to_hash` writes is deliberately not what `from_hash` accepts.
388
+
389
+ More importantly, the interesting parts of a mapping cannot be inverted automatically:
390
+
391
+ - **Type coercion is one-way.** `Types::Params::Integer.lax` turns `"3"` into `3`, but
392
+ nothing says whether the reverse should be `"3"`, `"3.0"`, or `3`. And because coercion
393
+ errors fall back to the raw value, the same type can even be a no-op for some inputs —
394
+ there is no function to invert.
395
+ - **Dynamic `as:` aliases depend on the instance.** `property :value, as: -> { key }` names
396
+ the output key from another attribute. Going backwards would mean guessing which incoming
397
+ key was produced by that lambda before the twin exists to evaluate it.
398
+ - **`getter:`/`setter:` lambdas are opaque.** They are arbitrary Ruby, so a getter that
399
+ joins, formats, or derives a value gives no way to compute the inverse. A `setter:` that
400
+ normalizes input cannot be run backwards to recover what came in.
401
+
402
+ So instead of one twin trying to be reversible, write each direction explicitly. Two small
403
+ twins are cheap, they document the API contract twice from the two perspectives that matter,
404
+ and each one keeps the coercions and defaults appropriate for its own direction — the
405
+ outbound payload and the inbound response often differ anyway (the response carries an `id`
406
+ and a `status` the request never sends).
407
+
408
+ ## Error Handling
409
+
410
+ Minitwin raises gem-specific exception classes so misuse of the DSL, of composition, of
411
+ dynamic aliases, of type coercion, and of the constructors can each be rescued on their own —
412
+ or all at once via the shared marker module:
413
+
414
+ ```ruby
415
+ begin
416
+ UserTwin.from_object({ id: 42 })
417
+ rescue Minitwin::Error => e
418
+ # any Minitwin-raised error, regardless of which of the five classes below
419
+ end
420
+ ```
421
+
422
+ | Class | Ruby base class | Raised when |
423
+ |---|---|---|
424
+ | `Minitwin::DefinitionError` | `ArgumentError` | The DSL itself is used incorrectly (e.g. an unknown option such as a misspelled `validatse:`, `nested` without a block, `setter:` together with a block, `validates:` without ActiveModel). |
425
+ | `Minitwin::CompositionError` | `RuntimeError` | A composition source given via `on:` is missing, or the source object doesn't respond to the composed property. |
426
+ | `Minitwin::AliasError` | `ArgumentError` | A dynamic alias (`as: -> { ... }`) is invalid, forbidden, or collides with another alias or an existing method. |
427
+ | `Minitwin::CoercionError` | `TypeError` | A value assigned to a block/nested property cannot be converted into that nested twin (or a custom `type:` callable raises it explicitly). |
428
+ | `Minitwin::ParseError` | `ArgumentError` | Input data is structurally unusable — malformed JSON in `from_json`, or a Hash passed to `from_object` instead of `from_objects`. |
429
+
430
+ `AliasError` (raised from the dynamic-alias checks) and `CompositionError` (raised from the
431
+ `on:` composition checks) keep their original Ruby base class unchanged — `ArgumentError` and
432
+ `RuntimeError` respectively — so existing `rescue ArgumentError` / `rescue RuntimeError` call
433
+ sites around those two paths are unaffected by this release.
434
+
435
+ Four previously-`RuntimeError` paths, however, now raise an `ArgumentError`/`TypeError`
436
+ sibling instead:
437
+
438
+ - `property ... setter: ->(v) { ... } do ... end` (a `setter:` combined with a block) —
439
+ now `Minitwin::DefinitionError` (`ArgumentError`)
440
+ - Assigning an unconvertible value to a block/nested property — now `Minitwin::CoercionError`
441
+ (`TypeError`)
442
+ - `validates:` used without ActiveModel available — now `Minitwin::DefinitionError`
443
+ (`ArgumentError`)
444
+ - `from_object` called with a Hash instead of `from_objects` — now `Minitwin::ParseError`
445
+ (`ArgumentError`)
446
+
447
+ Code that specifically rescued `RuntimeError` around any of these four call sites must widen
448
+ the rescue to `StandardError` / `Minitwin::Error`, or catch the new specific class, to keep
449
+ catching them. `Minitwin::Error` is an additional, more specific way to catch any of the five
450
+ classes above, not a replacement hierarchy.
451
+
452
+ This release ships three behavior changes relative to earlier versions:
453
+
454
+ 1. **`from_json` wraps malformed JSON.** A `JSON::ParserError` raised while parsing is now
455
+ wrapped into `Minitwin::ParseError`; the original error is still available via `#cause`:
456
+
457
+ ```ruby
458
+ begin
459
+ UserTwin.from_json("{not valid json")
460
+ rescue Minitwin::ParseError => e
461
+ e.cause #=> #<JSON::ParserError: ...>
462
+ end
463
+ ```
464
+
465
+ Code that rescued `JSON::ParserError` directly around `from_json` needs to rescue
466
+ `Minitwin::ParseError` (or `ArgumentError`) instead.
467
+
468
+ 2. **Four `RuntimeError` sites were reclassified**, as listed above — `rescue RuntimeError`
469
+ around them must be widened.
470
+
471
+ 3. **A custom `type:` callable that raises a `Minitwin::Error` subclass now propagates it**
472
+ instead of having it swallowed:
473
+
474
+ ```ruby
475
+ property :x, type: ->(v) { raise Minitwin::ParseError, "bad input" if v.blank?; v }
476
+ ```
477
+
478
+ Before this release: a `Minitwin::Error` raised inside a custom `type:` callable was
479
+ swallowed and the raw value returned. Now it propagates.
480
+
278
481
  ---
279
482
 
280
483
  ## DSL Reference
281
484
 
485
+ `property`, `collection` and `nested` accept only the options listed below. Any other option —
486
+ typically a typo such as `validatse:` — raises a `Minitwin::DefinitionError` when the class is
487
+ defined, naming the unknown option and the allowed ones. Before this release unknown options were
488
+ silently ignored; this includes `property`-only options passed to `collection` (e.g.
489
+ `collection :items, expose: false`), which never had an effect and now raise as well.
490
+
282
491
  ### `property`
283
492
 
284
493
  | Option | Description |
@@ -288,10 +497,11 @@ summary.name #=> "Dana"
288
497
  | `type:` | A dry-types type for coercion on assignment (e.g. `Types::Params::Integer.lax`). Errors fall back to the raw value. |
289
498
  | `twin:` | Wraps the value in another twin class. Accepts a hash, a twin instance, or an object with `to_h`/`attributes`. |
290
499
  | `expose:` | `false` omits the property from `to_hash`/`to_json`. |
500
+ | `expose_nil:` | `true` keeps the property in `to_hash`/`to_json` even when its value is `nil`, without turning on the global `render_nil:`. Combining `expose_nil: true` with `expose: false` raises an `ArgumentError`. |
291
501
  | `readonly:` | `true` prevents assignment via `assign_hash` and `assign_params`. |
292
502
  | `getter:` | A lambda `-> { ... }` or a symbol `:method_name` that fully replaces the generated getter. The lambda runs in instance context; the symbol calls the named method on the instance. If the lambda or method accepts a parameter, the current raw property value is passed as the argument. |
293
503
  | `setter:` | A lambda `->(value) { ... }` that fully replaces the generated setter. Not allowed together with a block. |
294
- | `on:` | Reads the value from a named composition source (see `from_objects`). |
504
+ | `on:` | Reads the value from a composition source (see `from_objects`), which can also be a nested twin. Accepts a symbol or a lambda `-> { ... }` returning the source. |
295
505
  | `validates:` | ActiveModel validation options, e.g. `{ presence: true }`. Ignored when ActiveModel is not available. |
296
506
  | block | Defines an inline nested twin class. Mutually exclusive with `setter:`. |
297
507
 
@@ -303,7 +513,7 @@ summary.name #=> "Dana"
303
513
  | `default:` | Default value. Defaults to `[]`. |
304
514
  | `twin:` | Wraps each element in the given twin class. |
305
515
  | `getter:` | A lambda `-> { ... }` or a symbol `:method_name` that fully replaces the generated getter. The lambda runs in instance context; the symbol calls the named method on the instance. If the lambda or method accepts a parameter, the current raw property value is passed as the argument. |
306
- | `on:` | Reads the collection from a named composition source. Each element is wrapped in the element twin when one is configured. |
516
+ | `on:` | Reads the collection from a composition source, which can also be a nested twin. Accepts a symbol or a lambda `-> { ... }`. Each element is wrapped in the element twin when one is configured. |
307
517
  | `validates:` | ActiveModel validation options applied to the collection property itself. |
308
518
  | block | Defines an inline nested twin class used for each element. |
309
519
 
@@ -356,7 +566,7 @@ The leaf properties (`city`, `zip`) are accessible directly on the parent instan
356
566
 
357
567
  | Method | Description |
358
568
  |---|---|
359
- | `to_hash(render_nil: false)` | Returns the twin as a Hash (or `HashWithIndifferentAccess` when ActiveSupport is available). Nested twins are serialized recursively. Unexposed properties are omitted. |
569
+ | `to_hash(render_nil: false)` | Returns the twin as a Hash (or `HashWithIndifferentAccess` when ActiveSupport is available). Nested twins are serialized recursively. Unexposed properties are omitted. `nil` values are dropped unless `render_nil: true` is passed, or the property was declared with `expose_nil: true`. |
360
570
  | `to_h` | Alias for `to_hash`. |
361
571
  | `to_json` | Delegates to `to_hash.to_json`. |
362
572
  | `attributes` | Returns a Hash keyed by the original setter names (before any `as:` aliasing). Includes protected readers. |
@@ -25,6 +25,8 @@ class Minitwin
25
25
  @allowed_attribute_keys_array = nil
26
26
  @setter_methods = nil
27
27
  @has_dynamic_aliases_cache = nil
28
+ @expose_nil_getters = nil
29
+ @expose_nil_property_keys = nil
28
30
  end
29
31
 
30
32
  def serializable_getters
@@ -41,6 +43,22 @@ class Minitwin
41
43
  end
42
44
  end
43
45
 
46
+ def expose_nil_property_keys
47
+ @expose_nil_property_keys ||= twin_class_hierarchy.each_with_object(Set.new) do |klass, keys|
48
+ klass.properties.each { |name, meta| keys << name if meta[:expose_nil] }
49
+ end
50
+ end
51
+
52
+ def expose_nil_getters
53
+ keys = expose_nil_property_keys
54
+ @expose_nil_getters ||=
55
+ if keys.empty?
56
+ Set.new
57
+ else
58
+ serializable_getters.select { |m| keys.include?(instance_method(m).original_name) }.to_set
59
+ end
60
+ end
61
+
44
62
  # Methods defined directly on the twin class hierarchy: this class and any
45
63
  # intermediate Minitwin subclasses, but not Minitwin itself. Methods mixed
46
64
  # in via modules (e.g. ActionView helpers, which include arg-taking methods
@@ -24,6 +24,8 @@ class Minitwin
24
24
  def from_json(body)
25
25
  hash = JSON.parse(body, symbolize_names: true)
26
26
  from_hash(hash)
27
+ rescue ::JSON::ParserError => exception
28
+ raise ParseError, "Invalid JSON passed to #{name}.from_json: #{exception.message}"
27
29
  end
28
30
 
29
31
  # Actually, this is expected to be an `ActionController::Parameters`
@@ -40,6 +42,7 @@ class Minitwin
40
42
  def from_object(model)
41
43
  if model.is_a?(Hash)
42
44
  raise(
45
+ ParseError,
43
46
  "Input is not an object. If you want to instantiate a Minitwin with multiple " \
44
47
  "objects, then use the pluralized 'from_objects'-method."
45
48
  )
@@ -30,6 +30,11 @@ class Minitwin
30
30
  @dynamic_nested_aliases ||= []
31
31
  end
32
32
 
33
+ # The DSL surface is limited to class body usage. Declaring it private
34
+ # here rather than in ClassMethods avoids Ruby's visibility stubs, which
35
+ # would shadow these signatures.
36
+ private
37
+
33
38
  # @rbs name: Symbol
34
39
  # @rbs validates: Hash[Symbol, untyped]
35
40
  # @rbs default: untyped
@@ -38,14 +43,17 @@ class Minitwin
38
43
  # @rbs twin: untyped
39
44
  # @rbs on: Symbol
40
45
  # @rbs return: void
41
- def collection(name, validates: {}, default: [], as: nil, getter: nil, twin: nil, on: nil, **_opts, &block)
46
+ def collection(name, validates: {}, default: [], as: nil, getter: nil, twin: nil, on: nil, **opts, &block)
47
+ reject_unknown_options!(:collection, name, opts)
48
+
42
49
  nested_class = block ? create_nested_class(name:, &block) : nil
43
50
  element_klass = twin || nested_class
51
+ ivar = Minitwin::Utils.ivar_name(name)
44
52
 
45
53
  define_method("#{name}=") do |values|
46
54
  arr = self.class.send(:coerce_collection_array, values)
47
55
  coerced_values = arr.map { |v| self.class.send(:coerce_value_to_twin, v, element_klass) }
48
- define_instance_variable(name:, value: coerced_values)
56
+ instance_variable_set(ivar, coerced_values)
49
57
  # :nocov:
50
58
  if !@__skip_alias_recompute__ && self.class.dynamic_aliases?
51
59
  __recompute_dynamic_aliases__
@@ -69,6 +77,7 @@ class Minitwin
69
77
  # @rbs default: untyped
70
78
  # @rbs as: Symbol | Proc
71
79
  # @rbs expose: bool
80
+ # @rbs expose_nil: bool
72
81
  # @rbs readonly: bool
73
82
  # @rbs type: untyped
74
83
  # @rbs getter: Proc
@@ -77,21 +86,31 @@ class Minitwin
77
86
  # @rbs on: Symbol
78
87
  # @rbs return: void
79
88
  def property(
80
- name, validates: {}, default: nil, as: nil, expose: true, readonly: false, type: nil, getter: nil, setter: nil,
81
- twin: nil, on: nil, **_opts, &block
89
+ name, validates: {}, default: nil, as: nil, expose: true, expose_nil: false, readonly: false, type: nil,
90
+ getter: nil, setter: nil, twin: nil, on: nil, **opts, &block
82
91
  )
92
+ reject_unknown_options!(:property, name, opts)
93
+
94
+ if expose_nil && !expose
95
+ raise(
96
+ DefinitionError,
97
+ "Property '#{name}' cannot combine `expose: false` with `expose_nil: true`."
98
+ )
99
+ end
100
+
83
101
  nested_class = nil
102
+ ivar = Minitwin::Utils.ivar_name(name)
84
103
 
85
104
  if block_given?
86
- raise "setters are not possible in blocks" if setter
105
+ raise DefinitionError, "setters are not possible in blocks" if setter
87
106
 
88
107
  nested_class = create_nested_class(name:, &block)
89
108
 
90
109
  define_method("#{name}=") do |value|
91
110
  coerced = self.class.send(:coerce_value_to_twin, value, nested_class)
92
- raise "Unprocessable input for property '#{name}'." unless coerced.nil? || coerced.is_a?(nested_class)
111
+ raise CoercionError, "Unprocessable input for property '#{name}'." unless coerced.nil? || coerced.is_a?(nested_class)
93
112
 
94
- define_instance_variable(name:, value: coerced)
113
+ instance_variable_set(ivar, coerced)
95
114
  if !@__skip_alias_recompute__ && self.class.dynamic_aliases?
96
115
  __recompute_dynamic_aliases__
97
116
  end
@@ -110,7 +129,7 @@ class Minitwin
110
129
  else
111
130
  value
112
131
  end
113
- define_instance_variable(name:, value: coerced_value)
132
+ instance_variable_set(ivar, coerced_value)
114
133
  if !@__skip_alias_recompute__ && self.class.dynamic_aliases?
115
134
  __recompute_dynamic_aliases__
116
135
  end
@@ -126,6 +145,7 @@ class Minitwin
126
145
  type: type,
127
146
  as: as,
128
147
  expose: expose,
148
+ expose_nil: expose_nil,
129
149
  readonly: readonly
130
150
  }
131
151
  properties[name.to_sym][:twin] = twin if twin
@@ -136,8 +156,9 @@ class Minitwin
136
156
  # @rbs name: Symbol
137
157
  # @rbs as: Symbol | Proc
138
158
  # @rbs return: void
139
- def nested(name, as: nil, &block)
140
- raise ArgumentError, "nested requires a block" unless block_given?
159
+ def nested(name, as: nil, **opts, &block)
160
+ reject_unknown_options!(:nested, name, opts)
161
+ raise DefinitionError, "nested requires a block" unless block_given?
141
162
 
142
163
  property(name, as: as, &block)
143
164
 
@@ -217,7 +238,20 @@ class Minitwin
217
238
  invalidate_caches
218
239
  end
219
240
 
220
- private
241
+ # Unknown options would otherwise be dropped silently, hiding typos
242
+ # such as `validatse:`. The allowed list is read from the DSL method's
243
+ # own signature so it cannot drift from it.
244
+ def reject_unknown_options!(dsl_method, name, opts)
245
+ return if opts.empty?
246
+
247
+ allowed = method(dsl_method).parameters.filter_map { |kind, key| key if kind == :key }
248
+ unknown = opts.keys.map { |key| "`#{key}:`" }.join(", ")
249
+ raise(
250
+ DefinitionError,
251
+ "Unknown option#{"s" if opts.size > 1} #{unknown} for #{dsl_method} '#{name}'. " \
252
+ "Allowed options: #{allowed.join(", ")}."
253
+ )
254
+ end
221
255
 
222
256
  def constantize_name(name)
223
257
  name.to_s.split("_").map(&:capitalize).join
@@ -244,8 +278,13 @@ class Minitwin
244
278
  end
245
279
 
246
280
  def define_getter_method(name:, as:, on:, default:, getter:, type: nil)
247
- getter_proc = build_getter_proc(name:, on:, default:, getter:, type:)
248
- define_method(name, &getter_proc)
281
+ if getter.nil? && on.nil? && default.nil? && type.nil? && !name.to_s.end_with?("?")
282
+ # Fast path: a plain property with no getter override
283
+ attr_reader(name)
284
+ else
285
+ getter_proc = build_getter_proc(name:, on:, default:, getter:, type:)
286
+ define_method(name, &getter_proc)
287
+ end
249
288
  apply_alias_to_getter(name:, as:)
250
289
  end
251
290
 
@@ -297,12 +336,13 @@ class Minitwin
297
336
  # Validate model
298
337
  if model.nil?
299
338
  raise(
339
+ CompositionError,
300
340
  "Property '#{name}' refers to unknown composition source '#{on}' in #{self.class}. " \
301
341
  "Ensure the model is provided via from_objects or a reader exists."
302
342
  )
303
343
  end
304
344
  unless model.respond_to?(name)
305
- raise "The instance of '#{model.class}' does not respond to '#{name}'."
345
+ raise CompositionError, "The instance of '#{model.class}' does not respond to '#{name}'."
306
346
  end
307
347
 
308
348
  raw = model.send(name)
@@ -363,7 +403,7 @@ class Minitwin
363
403
  return if validates.nil?
364
404
  return if validates.respond_to?(:empty?) && validates.empty?
365
405
 
366
- raise "Validation is not possible, because activemodel is not available" unless respond_to?(:validates)
406
+ raise DefinitionError, "Validation is not possible, because activemodel is not available" unless respond_to?(:validates)
367
407
 
368
408
  if validates.is_a?(Proc)
369
409
  validate do
@@ -62,6 +62,12 @@ class Minitwin
62
62
  return raw_value unless type
63
63
 
64
64
  type.call(raw_value)
65
+ rescue Minitwin::Error
66
+ # Re-raise: a Minitwin::Error (e.g. from a custom type: callable) must propagate
67
+ # instead of being swallowed by the broader rescue below, which is for ordinary
68
+ # coercion failures only. CoercionError/AliasError/ParseError/DefinitionError are
69
+ # all TypeError/ArgumentError subclasses, so this clause has to come first.
70
+ raise
65
71
  rescue *Minitwin.send(:coercion_error_classes)
66
72
  raw_value
67
73
  end
@@ -17,10 +17,8 @@ class Minitwin
17
17
  include Minitwin::ClassMethods::TypesHelper
18
18
  include Minitwin::ClassMethods::Coercion
19
19
 
20
- # Limit DSL surface to class body usage
21
- private :property, :collection, :nested
22
-
23
- # Make constructors and RBS API public
24
- public :from_hash, :from_json, :from_params, :from_object, :from_objects, :from_collection, :to_rbs
20
+ # The DSL surface is limited to class body usage by Minitwin::ClassMethods::Dsl
21
+ # itself; declaring it here would install visibility stubs that shadow the
22
+ # typed originals.
25
23
  end
26
24
  end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ class Minitwin
5
+ # Marker: `rescue Minitwin::Error` catches every gem-specific error.
6
+ module Error; end
7
+
8
+ # DSL used incorrectly — fails at class-definition time.
9
+ class DefinitionError < ::ArgumentError
10
+ include Error
11
+ end
12
+
13
+ # A source object cannot supply a composed property.
14
+ class CompositionError < ::RuntimeError
15
+ include Error
16
+ end
17
+
18
+ # A dynamic alias is invalid, forbidden, or collides.
19
+ class AliasError < ::ArgumentError
20
+ include Error
21
+ end
22
+
23
+ # A value cannot be coerced into the expected twin type.
24
+ class CoercionError < ::TypeError
25
+ include Error
26
+ end
27
+
28
+ # Input data is structurally unusable (JSON, wrong object type).
29
+ class ParseError < ::ArgumentError
30
+ include Error
31
+ end
32
+ end
@@ -138,7 +138,7 @@ class Minitwin
138
138
 
139
139
  def __apply_dynamic_alias__(target_method, alias_name)
140
140
  unless alias_name.is_a?(String) || alias_name.is_a?(Symbol)
141
- raise ArgumentError, "Invalid alias name #{alias_name.inspect}: must be a String or Symbol"
141
+ raise AliasError, "Invalid alias name #{alias_name.inspect}: must be a String or Symbol"
142
142
  end
143
143
 
144
144
  alias_key = alias_name.to_sym
@@ -147,7 +147,7 @@ class Minitwin
147
147
 
148
148
  # Security check: prevent aliasing to forbidden method names
149
149
  if FORBIDDEN_ALIAS_NAMES.include?(alias_key)
150
- raise ArgumentError, "Cannot define dynamic alias '#{alias_key}': forbidden method name for security reasons"
150
+ raise AliasError, "Cannot define dynamic alias '#{alias_key}': forbidden method name for security reasons"
151
151
  end
152
152
 
153
153
  prev = aliases[target_method]
@@ -162,11 +162,11 @@ class Minitwin
162
162
 
163
163
  # Collision checks: alias already used by another target or an existing method
164
164
  if aliases_rev.key?(alias_key) && aliases_rev[alias_key] != target_method
165
- raise ArgumentError, "Dynamic alias '#{alias_key}' already defined for '#{aliases_rev[alias_key]}'"
165
+ raise AliasError, "Dynamic alias '#{alias_key}' already defined for '#{aliases_rev[alias_key]}'"
166
166
  end
167
167
 
168
168
  if respond_to?(alias_key, true) && aliases_rev[alias_key] != target_method
169
- raise ArgumentError, "Cannot define dynamic alias '#{alias_key}': method already exists"
169
+ raise AliasError, "Cannot define dynamic alias '#{alias_key}': method already exists"
170
170
  end
171
171
 
172
172
  # Define forwarding method on the singleton class
@@ -16,10 +16,11 @@ class Minitwin
16
16
  hash = Minitwin.hash_klass.new
17
17
 
18
18
  methods_to_serialize = self.class.send(:serializable_getters)
19
+ expose_nil_getters = self.class.send(:expose_nil_getters)
19
20
 
20
21
  methods_to_serialize.each do |method|
21
22
  value = send(method)
22
- next if value.nil? && !render_nil
23
+ next if value.nil? && !render_nil && !expose_nil_getters.include?(method)
23
24
 
24
25
  hash[method] = transform_value_for_serialization(value)
25
26
  end
@@ -28,6 +29,8 @@ class Minitwin
28
29
  if instance_variable_defined?(ALIASES_VAR)
29
30
  aliases = instance_variable_get(ALIASES_VAR)
30
31
  if aliases && !aliases.empty?
32
+ expose_nil_keys = self.class.send(:expose_nil_property_keys)
33
+
31
34
  aliases.each do |target_method, alias_method|
32
35
  # Skip nested proxy aliases at the top level; nested groups
33
36
  # serialize under their container key only.
@@ -37,7 +40,7 @@ class Minitwin
37
40
  # the alias method is overridden. Apply the same transformation rules
38
41
  # as above for nested twins and arrays.
39
42
  value = send(target_method)
40
- next if value.nil? && !render_nil
43
+ next if value.nil? && !render_nil && !expose_nil_keys.include?(target_method)
41
44
 
42
45
  hash[alias_method] = transform_value_for_serialization(value)
43
46
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Minitwin
4
- VERSION = "1.0.0"
4
+ VERSION = "1.1.0"
5
5
  end
data/lib/minitwin.rb CHANGED
@@ -17,8 +17,11 @@ end
17
17
 
18
18
  # Setup Zeitwerk loader for the gem to support Rails autoloading
19
19
  loader = Zeitwerk::Loader.for_gem
20
+ loader.ignore("#{__dir__}/minitwin/errors.rb")
20
21
  loader.setup
21
22
 
23
+ require_relative "minitwin/errors"
24
+
22
25
  class Minitwin
23
26
  # Constants for internal variable naming
24
27
  INTERNAL_MODEL_PREFIX = "@internal_model__"
@@ -12,6 +12,10 @@ class Minitwin
12
12
 
13
13
  def serializable_getters: () -> untyped
14
14
 
15
+ def expose_nil_property_keys: () -> untyped
16
+
17
+ def expose_nil_getters: () -> untyped
18
+
15
19
  # Methods defined directly on the twin class hierarchy: this class and any
16
20
  # intermediate Minitwin subclasses, but not Minitwin itself. Methods mixed
17
21
  # in via modules (e.g. ActionView helpers, which include arg-taking methods
@@ -18,6 +18,8 @@ class Minitwin
18
18
  # : () -> Array[Hash]
19
19
  def dynamic_nested_aliases: () -> Array[Hash]
20
20
 
21
+ private
22
+
21
23
  # @rbs name: Symbol
22
24
  # @rbs validates: Hash[Symbol, untyped]
23
25
  # @rbs default: untyped
@@ -26,13 +28,14 @@ class Minitwin
26
28
  # @rbs twin: untyped
27
29
  # @rbs on: Symbol
28
30
  # @rbs return: void
29
- def collection: (Symbol name, ?validates: Hash[Symbol, untyped], ?default: untyped, ?as: untyped, ?getter: Proc, ?twin: untyped, ?on: Symbol, **untyped _opts) ?{ (?) -> untyped } -> void
31
+ def collection: (Symbol name, ?validates: Hash[Symbol, untyped], ?default: untyped, ?as: untyped, ?getter: Proc, ?twin: untyped, ?on: Symbol, **untyped opts) ?{ (?) -> untyped } -> void
30
32
 
31
33
  # @rbs name: Symbol
32
34
  # @rbs validates: Hash[Symbol, untyped]
33
35
  # @rbs default: untyped
34
36
  # @rbs as: Symbol | Proc
35
37
  # @rbs expose: bool
38
+ # @rbs expose_nil: bool
36
39
  # @rbs readonly: bool
37
40
  # @rbs type: untyped
38
41
  # @rbs getter: Proc
@@ -40,14 +43,17 @@ class Minitwin
40
43
  # @rbs twin: untyped
41
44
  # @rbs on: Symbol
42
45
  # @rbs return: void
43
- def property: (Symbol name, ?validates: Hash[Symbol, untyped], ?default: untyped, ?as: untyped, ?expose: bool, ?readonly: bool, ?type: untyped, ?getter: Proc, ?setter: Proc, ?twin: untyped, ?on: Symbol, **untyped _opts) ?{ (?) -> untyped } -> void
46
+ def property: (Symbol name, ?validates: Hash[Symbol, untyped], ?default: untyped, ?as: untyped, ?expose: bool, ?expose_nil: bool, ?readonly: bool, ?type: untyped, ?getter: Proc, ?setter: Proc, ?twin: untyped, ?on: Symbol, **untyped opts) ?{ (?) -> untyped } -> void
44
47
 
45
48
  # @rbs name: Symbol
46
49
  # @rbs as: Symbol | Proc
47
50
  # @rbs return: void
48
- def nested: (Symbol name, ?as: untyped) ?{ (?) -> untyped } -> void
51
+ def nested: (Symbol name, ?as: untyped, **untyped opts) ?{ (?) -> untyped } -> void
49
52
 
50
- private
53
+ # Unknown options would otherwise be dropped silently, hiding typos
54
+ # such as `validatse:`. The allowed list is read from the DSL method's
55
+ # own signature so it cannot drift from it.
56
+ def reject_unknown_options!: (untyped dsl_method, untyped name, untyped opts) -> untyped
51
57
 
52
58
  def constantize_name: (untyped name) -> untyped
53
59
 
@@ -0,0 +1,32 @@
1
+ # Generated from lib/minitwin/errors.rb with RBS::Inline
2
+
3
+ class Minitwin
4
+ # Marker: `rescue Minitwin::Error` catches every gem-specific error.
5
+ module Error
6
+ end
7
+
8
+ # DSL used incorrectly — fails at class-definition time.
9
+ class DefinitionError < ::ArgumentError
10
+ include Error
11
+ end
12
+
13
+ # A source object cannot supply a composed property.
14
+ class CompositionError < ::RuntimeError
15
+ include Error
16
+ end
17
+
18
+ # A dynamic alias is invalid, forbidden, or collides.
19
+ class AliasError < ::ArgumentError
20
+ include Error
21
+ end
22
+
23
+ # A value cannot be coerced into the expected twin type.
24
+ class CoercionError < ::TypeError
25
+ include Error
26
+ end
27
+
28
+ # Input data is structurally unusable (JSON, wrong object type).
29
+ class ParseError < ::ArgumentError
30
+ include Error
31
+ end
32
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: minitwin
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Johannes Balk
@@ -50,6 +50,7 @@ files:
50
50
  - lib/minitwin/class_methods/dsl.rb
51
51
  - lib/minitwin/class_methods/rbs.rb
52
52
  - lib/minitwin/class_methods/types_helper.rb
53
+ - lib/minitwin/errors.rb
53
54
  - lib/minitwin/initialization.rb
54
55
  - lib/minitwin/railtie.rb
55
56
  - lib/minitwin/serialization.rb
@@ -61,6 +62,7 @@ files:
61
62
  - sig/generated/minitwin/class_methods/constructors.rbs
62
63
  - sig/generated/minitwin/class_methods/dsl.rbs
63
64
  - sig/generated/minitwin/class_methods/rbs.rbs
65
+ - sig/generated/minitwin/errors.rbs
64
66
  - sig/generated/minitwin/initialization.rbs
65
67
  - sig/generated/minitwin/serialization.rbs
66
68
  - sig/generated/minitwin/sync.rbs
@@ -83,7 +85,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
83
85
  - !ruby/object:Gem::Version
84
86
  version: '0'
85
87
  requirements: []
86
- rubygems_version: 4.0.12
88
+ rubygems_version: 4.0.20
87
89
  specification_version: 4
88
90
  summary: Minimal presentation layer
89
91
  test_files: []