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.
Files changed (70) hide show
  1. checksums.yaml +4 -4
  2. data/.claude-plugin/marketplace.json +13 -0
  3. data/.claude-plugin/plugin.json +9 -0
  4. data/AGENTS.md +47 -54
  5. data/CHANGELOG.md +53 -640
  6. data/LICENSE.txt +21 -0
  7. data/README.md +33 -628
  8. data/USAGE.md +771 -715
  9. data/docs/getting_started.md +139 -325
  10. data/lib/field_struct/base.rb +241 -1149
  11. data/lib/field_struct/class_macros.rb +163 -0
  12. data/lib/field_struct/describer.rb +167 -0
  13. data/lib/field_struct/errors.rb +182 -62
  14. data/lib/field_struct/exceptions.rb +40 -0
  15. data/lib/field_struct/field.rb +69 -135
  16. data/lib/field_struct/field_builder.rb +110 -0
  17. data/lib/field_struct/field_checks.rb +50 -0
  18. data/lib/field_struct/introspection.rb +199 -0
  19. data/lib/field_struct/json_codec.rb +240 -0
  20. data/lib/field_struct/metadata.rb +65 -260
  21. data/lib/field_struct/model_name.rb +27 -27
  22. data/lib/field_struct/option_checker.rb +121 -0
  23. data/lib/field_struct/partial.rb +49 -0
  24. data/lib/field_struct/presence.rb +45 -0
  25. data/lib/field_struct/rbs.rb +151 -271
  26. data/lib/field_struct/registered_option.rb +113 -0
  27. data/lib/field_struct/registry.rb +40 -50
  28. data/lib/field_struct/restrictions.rb +90 -0
  29. data/lib/field_struct/scaffold.rb +274 -301
  30. data/lib/field_struct/suggestion.rb +33 -0
  31. data/lib/field_struct/types/array.rb +147 -126
  32. data/lib/field_struct/types/base.rb +113 -124
  33. data/lib/field_struct/types/big_decimal.rb +59 -55
  34. data/lib/field_struct/types/binary.rb +18 -25
  35. data/lib/field_struct/types/boolean.rb +74 -97
  36. data/lib/field_struct/types/builtin.rb +32 -0
  37. data/lib/field_struct/types/date.rb +23 -137
  38. data/lib/field_struct/types/datetime.rb +30 -139
  39. data/lib/field_struct/types/element_options.rb +51 -0
  40. data/lib/field_struct/types/email.rb +27 -38
  41. data/lib/field_struct/types/float.rb +58 -56
  42. data/lib/field_struct/types/format_presets.rb +30 -0
  43. data/lib/field_struct/types/hash.rb +144 -0
  44. data/lib/field_struct/types/immutable_string.rb +16 -9
  45. data/lib/field_struct/types/integer.rb +74 -102
  46. data/lib/field_struct/types/nested.rb +57 -58
  47. data/lib/field_struct/types/preset_resolver.rb +9 -24
  48. data/lib/field_struct/types/rfc3339_format.rb +70 -153
  49. data/lib/field_struct/types/string.rb +48 -46
  50. data/lib/field_struct/types/symbol.rb +23 -20
  51. data/lib/field_struct/types/temporal.rb +232 -0
  52. data/lib/field_struct/types/time.rb +32 -145
  53. data/lib/field_struct/types/union.rb +111 -65
  54. data/lib/field_struct/types/union_pick.rb +139 -0
  55. data/lib/field_struct/types/url.rb +24 -35
  56. data/lib/field_struct/types/uuid.rb +24 -35
  57. data/lib/field_struct/types/value.rb +14 -9
  58. data/lib/field_struct/types/zone.rb +118 -0
  59. data/lib/field_struct/version.rb +3 -3
  60. data/lib/field_struct.rb +102 -122
  61. data/sig/field_struct.rbs +1180 -2300
  62. data/sig/manifest.yaml +6 -0
  63. data/skills/field-struct/SKILL.md +73 -159
  64. metadata +37 -28
  65. data/CODE_OF_CONDUCT.md +0 -132
  66. data/UPGRADING.md +0 -743
  67. data/lib/field_struct/error.rb +0 -48
  68. data/lib/field_struct/types/temporal_parser.rb +0 -93
  69. data/lib/field_struct/types/time_format_resolver.rb +0 -54
  70. data/lib/field_struct/types/zone_option.rb +0 -267
@@ -0,0 +1,232 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Types
5
+ # INTERNAL base of +:date+, +:time+ and +:datetime+. Dispatches on explicit stdlib classes only and parses through
6
+ # the stdlib class methods, never through anything ActiveSupport redefines (FS-I6). Refuses rather than guesses (FS-I12).
7
+ class Temporal < Base
8
+ # Zone names read as UTC.
9
+ # @return [::Array<::String>]
10
+ UTC_TEXT = %w[Z UTC GMT UT].freeze
11
+ # Message tail for a zone name with no fixed offset.
12
+ # @return [::String]
13
+ NO_FIXED_OFFSET = 'names a time zone with no fixed offset, which zone: does not override'
14
+
15
+ class << self
16
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}] +format+, +in+ and (time family) +zone+
17
+ def own_option_schema
18
+ format_option = option(type: [::String, ::Symbol], presets: presets.keys)
19
+ range_option = option(type: [::Array, ::Range])
20
+ return { format: format_option, in: range_option } unless zoned?
21
+
22
+ { format: format_option, in: range_option, zone: option(type: ::String) }
23
+ end
24
+
25
+ # @return [nil] temporal types prefill +format: nil+ (FS-B7)
26
+ def default_format
27
+ nil
28
+ end
29
+
30
+ # @return [::Hash{::Symbol=>::Object}] preset name to strptime String (or RFC 3339 format object)
31
+ def presets
32
+ {}
33
+ end
34
+
35
+ # @return [Boolean] whether the type takes +zone:+
36
+ def zoned?
37
+ false
38
+ end
39
+
40
+ # Checks the preset name and the zone at declaration; the declared +format:+ is kept as written (FS-B15).
41
+ #
42
+ # @param options [::Hash{::Symbol=>::Object}]
43
+ # @return [::Hash{::Symbol=>::Object}] the same options
44
+ # @raise [ArgumentError] for an unknown preset or an invalid zone
45
+ def resolve_options(options, **)
46
+ PresetResolver.call(options, :format, presets, label: "#{preset_caption} format")
47
+ Zone.check!(options[:zone], short_name) if options[:zone]
48
+ options
49
+ end
50
+
51
+ # @param value [::Date, ::DateTime, ::Time]
52
+ # @return [::String] the fraction digits of the sub-second part, to nanoseconds, trailing zeros trimmed ('' when none)
53
+ def fraction_digits(value)
54
+ subsec = value.is_a?(::DateTime) ? value.sec_fraction : value.subsec
55
+ nanos = (subsec * 1_000_000_000).floor
56
+ nanos.zero? ? '' : nanos.to_s.rjust(9, '0').sub(/0+\z/, '')
57
+ end
58
+
59
+ # @return [::String] how preset errors name the type
60
+ def preset_caption
61
+ short_name.downcase
62
+ end
63
+ end
64
+
65
+ # @param value [::Object] nil, a String, a Date, DateTime or Time
66
+ # @param format [::String, ::Symbol, nil] a strptime String or preset name
67
+ # @param zone [::String, nil] what a zone-less string means
68
+ # @return [::Date, ::Time, ::DateTime, nil]
69
+ # @raise [ArgumentError] for anything refused
70
+ def coerce(value, format: nil, zone: nil, **)
71
+ coerce_with(value, format, zone)
72
+ end
73
+
74
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
75
+ #
76
+ # @param value [::Object]
77
+ # @param options [::Hash{::Symbol=>::Object}]
78
+ # @return [::Date, ::Time, ::DateTime, nil]
79
+ # @api private
80
+ def coerce_positional(value, options)
81
+ coerce_with(value, options[:format], options[:zone])
82
+ end
83
+
84
+ # Renders a value the way +as_json+ writes it: by +format:+ (RFC 3339 preset, strftime String) or ISO 8601.
85
+ #
86
+ # @param value [::Date, ::DateTime, ::Time]
87
+ # @param format [::String, ::Symbol, nil]
88
+ # @return [::String]
89
+ def render(value, format: nil, **)
90
+ spec = format_spec(format)
91
+ case spec
92
+ when nil then iso8601(value)
93
+ when ::String then value.strftime(spec)
94
+ else spec.render(value)
95
+ end
96
+ end
97
+
98
+ private
99
+
100
+ def coerce_with(value, format, zone)
101
+ return nil if value.nil?
102
+
103
+ spec = format_spec(format)
104
+ zone_object = zone && Zone.fetch(zone)
105
+ case value
106
+ when ::String then from_string(value, spec, zone_object)
107
+ when ::DateTime then from_datetime(value)
108
+ when ::Date then from_date(value, zone_object)
109
+ when ::Time then from_time(value)
110
+ else raise ::ArgumentError, "expected a String, Date, DateTime or Time, got #{value.class}"
111
+ end
112
+ end
113
+
114
+ def iso8601(value)
115
+ return value.iso8601 if value.is_a?(::Date) && !value.is_a?(::DateTime)
116
+
117
+ value.iso8601(self.class.fraction_digits(value).length)
118
+ end
119
+
120
+ def format_spec(format)
121
+ return format unless format.is_a?(::Symbol)
122
+
123
+ self.class.presets.fetch(format) do
124
+ raise ::ArgumentError, "unknown #{self.class.preset_caption} format preset #{format.inspect}. " \
125
+ "Available: #{self.class.presets.keys.inspect}"
126
+ end
127
+ end
128
+
129
+ def from_string(text, spec, zone)
130
+ components = case spec
131
+ when Rfc3339Format then spec.parse(text)
132
+ when ::String then strptime_components(text, spec, zone)
133
+ else free_components(text, zone)
134
+ end
135
+ components[:epoch] ? from_epoch(components[:epoch], zone) : assemble(components, zone)
136
+ end
137
+
138
+ # No format: the string must name a whole, existing day (FS-B87).
139
+ def free_components(text, zone)
140
+ parts = ::Date._parse(text)
141
+ raise ::ArgumentError, 'expected a date with a year, a month and a day' unless parts[:year] && parts[:mon] && parts[:mday]
142
+ raise ::ArgumentError, 'invalid date' unless ::Date.valid_date?(parts[:year], parts[:mon], parts[:mday])
143
+
144
+ time_parts(parts).merge(year: parts[:year], mon: parts[:mon], mday: parts[:mday], offset: offset_of(parts, zone))
145
+ end
146
+
147
+ # A declared format anchors: the whole string must match (FS-B88).
148
+ def strptime_components(text, format, zone)
149
+ parts = strptime(text, format)
150
+ return { epoch: parts[:seconds] } if parts[:seconds]
151
+
152
+ time_parts(parts).merge(date_parts(parts, zone)).merge(offset: offset_of(parts, zone))
153
+ end
154
+
155
+ def strptime(text, format)
156
+ parts = ::Date._strptime(text, format) unless text.match?(/\A\s/) && !format.match?(/\A\s/)
157
+ raise ::ArgumentError, "does not match format #{format.inspect}" if parts.nil?
158
+ raise ::ArgumentError, "does not match format #{format.inspect} — unexpected trailing characters" if parts[:leftover]
159
+
160
+ parts
161
+ end
162
+
163
+ def date_parts(parts, zone)
164
+ today = today_in(zone)
165
+ if parts[:yday] && !parts[:mon] && !parts[:mday]
166
+ year = parts[:year] || today[0]
167
+ raise ::ArgumentError, 'invalid date' unless ::Date.valid_ordinal?(year, parts[:yday])
168
+
169
+ day = ::Date.ordinal(year, parts[:yday])
170
+ return { year: day.year, mon: day.mon, mday: day.mday }
171
+ end
172
+ year, mon, mday = fill_date(parts.values_at(:year, :mon, :mday), today)
173
+ raise ::ArgumentError, 'invalid date' unless ::Date.valid_date?(year, mon, mday)
174
+
175
+ { year: year, mon: mon, mday: mday }
176
+ end
177
+
178
+ # Units above the most significant written one come from today, units below it start at 1.
179
+ def fill_date(given, today)
180
+ first = given.index { |unit| !unit.nil? }
181
+ return today if first.nil?
182
+
183
+ given.each_with_index.map { |unit, index| unit || (index < first ? today[index] : 1) }
184
+ end
185
+
186
+ def today_in(zone)
187
+ now = zone ? zone.time_at_epoch(::Time.now.to_r) : ::Time.now
188
+ [now.year, now.mon, now.mday]
189
+ end
190
+
191
+ def time_parts(parts)
192
+ hour, min, sec = parts.values_at(:hour, :min, :sec).map { |unit| unit || 0 }
193
+ raise ::ArgumentError, 'invalid time of day' if hour > 23 || min > 59 || sec > 59
194
+
195
+ { hour: hour, min: min, sec: sec, subsec: parts[:sec_fraction] || 0 }
196
+ end
197
+
198
+ # The offset a string carries: :utc for Z/UTC/GMT, seconds for others, nil for none.
199
+ def offset_of(parts, zone)
200
+ if parts[:offset]
201
+ return UTC_TEXT.include?(parts[:zone].to_s.upcase) ? :utc : parts[:offset]
202
+ end
203
+ raise ::ArgumentError, NO_FIXED_OFFSET if parts[:zone] && zone
204
+
205
+ nil
206
+ end
207
+
208
+ # A plain Time for string components: an offset the string carries wins, then the declared zone, then the default.
209
+ def time_from(components, zone)
210
+ args = components.values_at(:year, :mon, :mday, :hour, :min)
211
+ args << (components[:sec] + components[:subsec])
212
+ case (offset = components[:offset])
213
+ when :utc then ::Time.utc(*args)
214
+ when ::Integer then ::Time.new(*args, offset)
215
+ else zone ? zone.time_at_local(*args) : default_time(*args)
216
+ end
217
+ end
218
+
219
+ def default_time(*)
220
+ ::Time.utc(*)
221
+ end
222
+
223
+ def from_epoch(seconds, zone)
224
+ from_time(zone ? zone.time_at_epoch(seconds) : epoch_time(seconds))
225
+ end
226
+
227
+ def epoch_time(seconds)
228
+ ::Time.at(seconds)
229
+ end
230
+ end
231
+ end
232
+ end
@@ -1,167 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'time'
4
- require_relative 'base'
5
-
6
3
  module FieldStruct
7
4
  module Types
8
- # Time type. Returns a +Time+ as-is, builds one from a +Date+ or
9
- # +DateTime+'s components, reads a String via +Time.parse+ (or +strptime+
10
- # when the field declares a +format:+), and refuses everything else.
11
- #
12
- # Per-field +format:+ option (String or Symbol-preset) controls both
13
- # parsing (strptime when input is a String) and serialization
14
- # (strftime via +as_json+).
15
- class Time < Base
16
- # Native options: a +format:+ strftime/strptime String (or Symbol
17
- # preset; see {.presets}), an +in:+ Array or Range of allowed values,
18
- # and a +zone:+ String (+"UTC"+, +"±HH:MM"+ or an IANA name; see {ZoneOption}).
19
- #
20
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
21
- def self.own_option_schema
22
- {
23
- format: option(type: [::String, ::Symbol], presets: presets.keys),
24
- in: option(type: [::Array, ::Range]),
25
- zone: option(type: [::String])
26
- }
27
- end
28
-
29
- # @return [::String, nil]
30
- def self.default_format
31
- nil
32
- end
33
-
34
- # Named presets for the +format:+ option.
35
- #
36
- # +:iso8601+ is an {Rfc3339Format} rather than a strftime String: +%z+
37
- # renders +\+0000+, which RFC 3339 rejects, and no strftime string can
38
- # express optional fractional seconds. The interchange and display
39
- # presets stay strftime-based.
40
- #
41
- # @return [Hash{::Symbol=>Object}]
42
- def self.presets
43
- {
44
- iso8601: Rfc3339Format.timestamp,
45
- rfc2822: '%a, %d %b %Y %H:%M:%S %z',
46
- db: '%Y-%m-%d %H:%M:%S'
47
- }
48
- end
49
-
50
- # Validate a Symbol +format:+ preset (see {.presets}) and a +zone:+
51
- # (see {ZoneOption}) at field-declaration time.
52
- #
53
- # @param options [::Hash{::Symbol => Object, nil}] the per-field options
54
- # @return [::Hash{::Symbol => Object, nil}] the options, unchanged
55
- # @raise [ArgumentError] on an unknown preset or an unreadable +zone:+
56
- def self.resolve_options(options)
57
- ZoneOption.validate!('Time', TimeFormatResolver.call(options, presets))
58
- end
59
-
60
- # Resolve a declared +format:+ (a Symbol preset name or a strftime
61
- # String) into the String that {#coerce} and JSON rendering actually
62
- # use. Declarations are stored exactly as written, so this is where a
63
- # preset name becomes usable. See {TimeFormatResolver}.
64
- #
65
- # @param format [::String, ::Symbol, nil] the format as declared
66
- # @return [::String, nil] +nil+ when the field declares no format
67
- # @raise [ArgumentError] when a Symbol names no preset in {.presets}
68
- def self.resolve_format(format)
69
- # Skip building the presets Hash for the common, undeclared case.
70
- return format if format.nil? || format.is_a?(::String)
71
-
72
- TimeFormatResolver.resolve(format, presets)
73
- end
74
-
75
- # Dispatch is on explicit stdlib classes, never on a +respond_to?+ probe
76
- # against the value. ActiveSupport defines +String#to_time+, and it
77
- # returns +nil+ for a string with no time in it rather than raising — so
78
- # under Rails "not-a-time" was coerced to nil and reported VALID. The
79
- # probe is gone; +Time.parse+ and +Time.strptime+ behave the same with or
80
- # without ActiveSupport loaded.
81
- #
82
- # Cross-class conversion builds a Time from components rather than
83
- # calling +to_time+, which ActiveSupport redefines: under AS 7.2
84
- # +DateTime#to_time+ converts to the system-local zone and emits a
85
- # deprecation warning, while 8.x preserves the offset. Constructing from
86
- # parts gives the same instant and the same offset in all three
87
- # environments, which is what makes the behaviour host-independent rather
88
- # than merely documented.
89
- #
90
- # @param value [::String, ::Time, ::Date, ::DateTime, nil] +nil+ → +nil+;
91
- # a String is read through +strptime+ when a +format:+ is set and
92
- # +Time.parse+ otherwise; a +Time+ passes through; a +DateTime+, +Date+
93
- # or Time-like value (ActiveSupport's TimeWithZone) is converted.
94
- # Anything else is refused.
95
- # @param format [::String, nil] strptime/strftime format; +nil+ uses
96
- # {.default_format} (which itself defaults to +nil+ = ISO-8601 path)
97
- # @param zone [::String, nil] +"UTC"+, +"±HH:MM"+ or an IANA name: the offset for a
98
- # String that names none, and for a +Date+'s midnight. Input carrying
99
- # its own offset keeps it. +nil+ means the process zone. See {ZoneOption}.
100
- # @return [::Time, nil]
101
- # @raise [ArgumentError] when a String cannot be parsed, or the value is
102
- # not a String or a temporal object
103
- def coerce(value, format: self.class.default_format, zone: nil, **)
104
- return nil if value.nil?
105
-
106
- fmt = self.class.resolve_format(format)
5
+ # An instant with an offset. A zone-less string lands in the process zone, or in +zone:+ when declared.
6
+ class Time < Temporal
7
+ # Named formats the +format:+ option accepts (strptime Strings, or the RFC 3339 reader).
8
+ # @return [::Hash{::Symbol=>::Object}]
9
+ PRESETS = { iso8601: Rfc3339Format::TIMESTAMP, rfc2822: '%a, %d %b %Y %H:%M:%S %z', db: '%Y-%m-%d %H:%M:%S' }.freeze
10
+
11
+ class << self
12
+ # @return [::Hash{::Symbol=>::Object}] +iso8601+ (RFC 3339), +rfc2822+ and +db+
13
+ def presets
14
+ PRESETS
15
+ end
107
16
 
108
- case value
109
- when ::String then parse_string(value, fmt, zone)
110
- # ::DateTime before ::Date — DateTime is a subclass of Date, and only
111
- # this arm carries the time of day.
112
- when ::DateTime then time_from_datetime(value)
113
- when ::Date then zone ? ZoneOption.midnight(value, zone) : ::Time.new(value.year, value.mon, value.mday)
114
- # A TimeWithZone matches here (AS overrides Time.===) but is NOT an
115
- # instance of ::Time, so it must be converted rather than passed
116
- # through — otherwise a :time field would store a TWZ.
117
- when ::Time then value.instance_of?(::Time) ? value : ::Time.at(value.to_r).getlocal(value.utc_offset)
118
- else
119
- # The class, never the value — see Types::Date#coerce.
120
- raise ArgumentError, "expected a String, Date, DateTime or Time, got #{value.class}"
17
+ # @return [true]
18
+ def zoned?
19
+ true
121
20
  end
122
21
  end
123
22
 
124
- # @return [Class] the top-level +::Time+ class
23
+ # @return [::Class]
125
24
  def ruby_type
126
25
  ::Time
127
26
  end
128
27
 
129
28
  private
130
29
 
131
- # @param value [::String] the raw string
132
- # @param format [::String, nil] strptime format, when the field declares one
133
- # @param zone [::String, nil] the field's +zone:+, if declared
134
- # @return [::Time]
135
- # @raise [ArgumentError] when the string cannot be read
136
- def parse_string(value, format, zone)
137
- # Validated first, then handed to the stdlib parser: the checks decide
138
- # what is ACCEPTABLE, the stdlib still decides what the value IS, so
139
- # the two can't drift apart. See {TemporalParser} for the three rules.
140
- if format.is_a?(Rfc3339Format)
141
- parts = format.parse(value)
142
- return ::Time.new(parts[:year], parts[:mon], parts[:mday], parts[:hour], parts[:min],
143
- parts[:sec] + parts[:sec_fraction], parts[:offset])
144
- end
145
-
146
- if format
147
- parts = TemporalParser.strptime_parts(value, format)
148
- return ZoneOption.time_at(value, format, zone, parts) if zone && ZoneOption.zoneless?(parts)
30
+ def default_time(*)
31
+ ::Time.local(*)
32
+ end
149
33
 
150
- return ::Time.strptime(value, format)
151
- end
34
+ def assemble(components, zone)
35
+ time_from(components, zone)
36
+ end
152
37
 
153
- parts = TemporalParser.parse_parts(value)
154
- return ZoneOption.time_at(value, nil, zone, parts) if zone && ZoneOption.zoneless?(parts)
38
+ def from_datetime(value)
39
+ ::Time.new(value.year, value.mon, value.mday, value.hour, value.min, value.sec + value.sec_fraction,
40
+ (value.offset * 86_400).to_i)
41
+ end
155
42
 
156
- ::Time.parse(value)
43
+ def from_date(value, zone)
44
+ zone ? zone.start_of_day(value.year, value.mon, value.mday) : ::Time.local(value.year, value.mon, value.mday)
157
45
  end
158
46
 
159
- # @param value [::DateTime] the value to convert
160
- # @return [::Time] the same instant, at the same offset, sub-second
161
- # precision preserved
162
- def time_from_datetime(value)
163
- ::Time.new(value.year, value.mon, value.mday, value.hour, value.min,
164
- value.sec + value.sec_fraction, value.zone)
47
+ def from_time(value)
48
+ return value if value.instance_of?(::Time)
49
+
50
+ rebuilt = ::Time.at(value.to_r)
51
+ value.utc? ? rebuilt.utc : rebuilt.localtime(value.utc_offset)
165
52
  end
166
53
  end
167
54
  end
@@ -1,95 +1,141 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'base'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # Union type — a value that may be any of several types. Each
8
- # member is tried in declared order; the first one whose +coerce+
9
- # doesn't raise wins. Member-coercion errors are caught broadly
10
- # (ArgumentError, TypeError, FieldStruct::Error) so a member's
11
- # rejection lets the next member have a try; unrelated bugs (e.g.
12
- # +NoMethodError+) still propagate.
13
- #
14
- # optional :payload, :union, of: [Payload, :boolean]
15
- #
16
- # If every member rejects the value, the union raises a +TypeError+
17
- # which the parent's +coercion_policy+ handles like any
18
- # shape-level coercion failure.
19
- #
20
- # Order matters: +of: [String, Integer]+ coerces "42" to "42"
21
- # (String wins first); +of: [Integer, String]+ coerces "42" to 42.
5
+ # One of several types: members are tried in declared order and the first that accepts the value wins.
22
6
  class Union < Base
23
- # Member-coercion errors caught so the next member can be tried; other
24
- # exceptions (e.g. +NoMethodError+) propagate as real bugs.
25
- #
26
- # @return [::Array<Class<::StandardError>>]
27
- RESCUABLE = [ArgumentError, TypeError, FieldStruct::Error].freeze
7
+ # Failures that mean "this member refused the value"; anything else is a bug and propagates.
8
+ # @return [::Array<::Class>]
9
+ RESCUABLE = [::ArgumentError, ::TypeError, ::RangeError, FieldStruct::Error].freeze
28
10
 
29
- # Native options: a required +of:+ Array of member types (the DSL
30
- # additionally requires at least two members).
31
- #
32
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
33
- def self.own_option_schema
34
- {of: option(type: [::Array], required: true)}
11
+ # Declaration error for an +:array+ union member.
12
+ # @return [::String]
13
+ ARRAY_MEMBER = 'union `of:` cannot include :array (an array member would have no element type); ' \
14
+ 'give the array its own field or use :value'
15
+ # Declaration error for a +:hash+ union member.
16
+ # @return [::String]
17
+ HASH_MEMBER = 'union `of:` cannot include :hash (a hash member would have no value type); ' \
18
+ 'give the hash its own field or use :value'
19
+
20
+ class << self
21
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}]
22
+ def own_option_schema
23
+ { of: option(type: ::Array, required: true), discriminator: option(type: [::Symbol, ::Hash]) }
24
+ end
25
+
26
+ # @param _key [::Symbol]
27
+ # @return [::String]
28
+ def required_option_message(_key)
29
+ 'union field requires an `of: [...]` option naming the member types'
30
+ end
31
+
32
+ # Turns the member names and classes into type instances, in +options[:of]+.
33
+ #
34
+ # @param options [::Hash{::Symbol=>::Object}]
35
+ # @param registry [FieldStruct::Registry]
36
+ # @return [::Hash{::Symbol=>::Object}]
37
+ # @raise [ArgumentError, KeyError] for too few members, an array member, or an unknown name
38
+ def resolve_options(options, registry:, **)
39
+ members = options[:of]
40
+ raise ::ArgumentError, 'union `of:` must have at least two members' if members.size < 2
41
+
42
+ options.merge(of: members.map { |member| member_instance(member, registry) })
43
+ end
44
+
45
+ # The members live on the instance, so they leave the stored options. A +discriminator:+ is checked here and
46
+ # stays in the options as declared (FS-B83b).
47
+ #
48
+ # @param options [::Hash{::Symbol=>::Object}] resolved options
49
+ # @return [Array(FieldStruct::Types::Union, ::Hash{::Symbol=>::Object})] the instance and the options to store
50
+ # @raise [ArgumentError] for a +discriminator:+ that does not fit the members
51
+ def instantiate(options)
52
+ union = new(options[:of])
53
+ declared = options[:discriminator]
54
+ union.send(:use_discriminator, UnionPick::Discriminator.build(declared, options[:of])) if declared
55
+ [union, options.except(:of)]
56
+ end
57
+
58
+ private
59
+
60
+ def member_instance(member, registry)
61
+ klass = member.is_a?(::Class) ? member : registry.lookup(member)
62
+ raise ::ArgumentError, ARRAY_MEMBER if klass <= Types::Array
63
+ raise ::ArgumentError, HASH_MEMBER if klass <= Types::Hash
64
+ return Nested.new(klass, reads: false) if klass <= FieldStruct::Base
65
+ unless klass <= Types::Base
66
+ raise ::ArgumentError, "#{klass.inspect} is not a FieldStruct type (subclass FieldStruct::Types::Base)"
67
+ end
68
+
69
+ klass.new
70
+ end
35
71
  end
36
72
 
37
- # @return [Array<Types::Base>] the configured member type instances
73
+ # @return [::Array<FieldStruct::Types::Base>] the member type instances in declared order (read-only)
38
74
  attr_reader :member_types
39
75
 
40
- # @param member_types [Array<Types::Base>] member instances, in priority order
41
- def initialize(member_types)
76
+ # @param member_types [::Array<FieldStruct::Types::Base>]
77
+ def initialize(member_types = [])
42
78
  super()
43
79
  @member_types = member_types
80
+ @discriminator = nil
44
81
  end
45
82
 
46
- # @param value [Object, nil] anything — each member type's coerce
47
- # is tried in declared order; the first that doesn't raise wins
48
- # @return [Object, nil] whatever the first successful member returns
49
- # @raise [TypeError] when no member can coerce, or the value is a
50
- # non-finite number (NaN or ±Infinity), which no member may accept
83
+ # @param value [::Object]
84
+ # @return [::Object, nil] the first member's result
85
+ # @raise [TypeError] for a non-finite number, or when every member refuses
51
86
  def coerce(value, **)
52
87
  return nil if value.nil?
53
- # Refused before any member sees it: a numeric member rejects a
54
- # non-finite value with an ArgumentError, which is RESCUABLE, so a
55
- # later :string member would otherwise store "NaN" as valid.
56
- if value.is_a?(::Numeric) && !value.finite?
57
- # The class, never the value — see Types::Time#coerce.
58
- raise ::TypeError, "Union fields expect a finite number, got a non-finite #{value.class}"
59
- end
60
88
 
61
- @member_types.each do |type|
62
- return type.coerce(value)
89
+ refuse_non_finite(value)
90
+ members = member_types
91
+ if value.is_a?(::Hash)
92
+ picked, members = hash_pick(value)
93
+ return picked unless picked.equal?(UnionPick::NONE)
94
+ end
95
+ members.each do |member|
96
+ return member.coerce(value)
63
97
  rescue *RESCUABLE
64
98
  next
65
99
  end
66
-
67
- # The class, never the value — it may be payments data.
68
- members = @member_types.map { |m| m.class.name.to_s.split('::').last }.join(' | ')
69
- raise ::TypeError, "no union member (#{members}) could coerce #{value.class} input"
100
+ raise ::TypeError, "no union member (#{member_types.map { |m| m.class.short_name }.join(' | ')}) could coerce #{value.class} input"
70
101
  end
71
102
 
72
- # @param value [Object]
73
- # @return [Boolean] true only for nil — union doesn't try to
74
- # collectively reason about "missing" across its members
75
- def missing?(value)
76
- value.nil?
103
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
104
+ #
105
+ # @param value [::Object]
106
+ # @param _options [::Hash{::Symbol=>::Object}] unused: this type takes no options
107
+ # @return [::Object, nil]
108
+ # @api private
109
+ def coerce_positional(value, _options)
110
+ coerce(value)
77
111
  end
78
112
 
79
- # Flat list of member +ruby_type+ values. Members whose
80
- # ruby_type is already an Array (like Boolean's
81
- # +[TrueClass, FalseClass]+) get spliced in; duplicates are
82
- # removed.
83
- #
84
- # @return [Array<Class>]
113
+ # @return [::Array<::Class>] the members' classes, flattened and de-duplicated
85
114
  def ruby_type
86
- @member_types.flat_map { |type| Array(type.ruby_type) }.uniq
115
+ member_types.flat_map { |member| [member.ruby_type].flatten }.uniq
87
116
  end
88
117
 
89
- # @return [::String]
90
- def inspect
91
- members = @member_types.map { |m| m.class.name.to_s.split('::').last }.join(' | ')
92
- "#<#{FieldStruct.inspect_namespace}::Types::Union of=#{members}>"
118
+ private
119
+
120
+ def use_discriminator(discriminator)
121
+ @discriminator = discriminator
122
+ end
123
+
124
+ # The tag's member, or the ordered scan's pick among two or more struct members; with the members left to try.
125
+ def hash_pick(value)
126
+ return [@discriminator.pick(value), []] if @discriminator
127
+
128
+ structs = member_types.grep(Nested)
129
+ return [UnionPick::NONE, member_types] if structs.size < 2
130
+
131
+ [UnionPick.scan(structs, value, RESCUABLE), member_types - structs]
132
+ end
133
+
134
+ def refuse_non_finite(value)
135
+ return unless value.is_a?(::Float) || value.is_a?(::BigDecimal)
136
+ return if value.finite?
137
+
138
+ raise ::TypeError, "Union fields expect a finite number, got a non-finite #{value.class}"
93
139
  end
94
140
  end
95
141
  end