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
@@ -1,155 +1,176 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'base'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # Array type. Coerces each element through the registered element
8
- # type named by the +:of+ DSL option (resolved at field-declaration
9
- # time and stashed as +options[:of_type]+ — a class, not a symbol).
10
- #
11
- # An optional +:element+ Hash carries the element type's own options
12
- # (+strict:+, +base:+, +format:+, …), passed to every element's coerce:
13
- #
14
- # optional :ids, :array, of: :integer, element: {strict: true, base: 16}
15
- #
16
- # A refused element is reported with its index — +element at index 2: …+ —
17
- # and several with all of theirs (see {.elements_at}).
18
- #
19
- # Missing: +nil+ or empty array. ruby_type: +::Array+.
5
+ # A list whose elements are all coerced by one element type. A refused element fails the whole array.
20
6
  class Array < Base
21
- # Native options: a required +of:+ naming the element type — a
22
- # registered Symbol or a Class (a +Types::Base+ or +FieldStruct::Base+
23
- # subclass) — and an +element:+ Hash of that element type's options.
24
- #
25
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
26
- def self.own_option_schema
27
- {
28
- of: option(type: [::Symbol, ::Class], required: true),
29
- element: option(type: [::Hash])
30
- }
31
- end
7
+ # Index phrases name at most this many indexes.
8
+ # @return [::Integer]
9
+ MAX_INDEXES_SHOWN = 5
32
10
 
33
- # The element type class behind an +of_type+ option, whether it holds
34
- # a class (+:integer+ → {Types::Integer}) or a built instance (a
35
- # {Types::Nested}). Its +option_schema+ is what +element:+ accepts.
36
- #
37
- # @param of_type [Class, Types::Base] an array field's +:of_type+ option
38
- # @return [Class<Types::Base>] a {Types::Base} subclass
39
- def self.element_class(of_type)
40
- of_type.is_a?(::Class) ? of_type : of_type.class
41
- end
11
+ # Raised for a lazy source on an array of mirrors with no +max_items:+; the setter names the field (FS-B169).
12
+ # @api private
13
+ class Unbounded < FieldStruct::Error; end
42
14
 
43
- # @param value [::Array<Object, nil>, nil] anything else raises TypeError
44
- # @param of_type [Class, Types::Base, nil] the element type — a
45
- # Types::Base subclass for stock types, or an already-built
46
- # instance for parameterized types like {Types::Nested}. The DSL
47
- # stashes this when the user writes +of: :string+ / +of: SomeStruct+.
48
- # Required at the type level; nil here means the type was called
49
- # directly without DSL help.
50
- # @param element [::Hash{::Symbol => Object, nil}, nil] the element
51
- # type's options, passed to every element's coerce (the DSL's
52
- # +element:+, already validated against the element type's schema)
53
- # @return [::Array<Object, nil>, nil] each element coerced by +of_type+
54
- # @raise [TypeError] when input is non-nil and not an Array
55
- # @raise [ArgumentError] when +of_type+ is missing
56
- # @raise [StandardError] whatever the element type raises on a bad
57
- # element; an ArgumentError, TypeError or RangeError keeps its class
58
- # and gains an +element at index N: + prefix — or, when several
59
- # elements are refused, +elements at index N, M (index N shown): +
60
- def coerce(value, of_type: nil, element: nil, **)
61
- return nil if value.nil?
62
- raise ::TypeError, "expected Array, got #{value.class}" unless value.is_a?(::Array)
63
- raise ArgumentError, 'array coerce requires of_type:' if of_type.nil?
64
-
65
- element_type = element_type_for(of_type)
66
- # A manual index and no empty **splat keep this hot loop as cheap as it
67
- # was before element options (each_with_index.map + **{} cost ~40%).
68
- index = -1
69
- value.map do |item|
70
- index += 1
71
- element ? element_type.coerce(item, **element) : element_type.coerce(item)
72
- rescue ArgumentError, ::TypeError, ::RangeError => e
73
- # Off the hot loop: only a refused array pays for finding the rest.
74
- raise_refused!(value, index, e, element_type, element)
15
+ NO_ELEMENT_OPTIONS = {}.freeze
16
+ private_constant :NO_ELEMENT_OPTIONS
17
+
18
+ class << self
19
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}]
20
+ def own_option_schema
21
+ {
22
+ of: option(type: [::Symbol, ::String, ::Class], required: true),
23
+ element: option(type: ::Hash),
24
+ max_items: option(type: ::Integer)
25
+ }
26
+ end
27
+
28
+ # @param _key [::Symbol]
29
+ # @return [::String]
30
+ def required_option_message(_key)
31
+ 'array field requires an `of:` option naming the element type'
32
+ end
33
+
34
+ # Replaces +of:+ by +of_type:+ (a type class, or a Nested instance for a struct) and validates +element:+.
35
+ #
36
+ # @param options [::Hash{::Symbol=>::Object}]
37
+ # @param registry [FieldStruct::Registry]
38
+ # @param field_name [::Symbol]
39
+ # @return [::Hash{::Symbol=>::Object}]
40
+ # @raise [ArgumentError, KeyError] for an unknown element type or bad element options
41
+ def resolve_options(options, registry:, field_name:)
42
+ check_max_items(options[:max_items])
43
+ of_type = element_type_for(options[:of], registry)
44
+ resolved = { of_type: of_type }.merge(options.except(:of, :element))
45
+ element = ElementOptions.call(element_class(of_type), options[:element], registry: registry, field_name: field_name)
46
+ element ? resolved.merge(element: element) : resolved
47
+ end
48
+
49
+ # @param of_type [::Class, FieldStruct::Types::Base] a type class or a Nested instance
50
+ # @return [::Class] the element type's class
51
+ def element_class(of_type)
52
+ of_type.is_a?(::Class) ? of_type : of_type.class
53
+ end
54
+
55
+ # Renders which elements a message is about.
56
+ #
57
+ # @param indexes [::Array<::Integer>] 0-based
58
+ # @return [::String] +element at index 1+ or +elements at index 1, 4+ (five at most, then +and N more+)
59
+ def elements_at(indexes)
60
+ return "element at index #{indexes.first}" if indexes.size == 1
61
+
62
+ shown = indexes.first(MAX_INDEXES_SHOWN).join(', ')
63
+ extra = indexes.size - MAX_INDEXES_SHOWN
64
+ "elements at index #{shown}#{" and #{extra} more" if extra.positive?}"
65
+ end
66
+
67
+ private
68
+
69
+ def check_max_items(limit)
70
+ return if limit.nil? || limit >= 0
71
+
72
+ raise ::ArgumentError, "max_items: on Array takes a whole number from 0, got #{limit}"
73
+ end
74
+
75
+ def element_type_for(of, registry)
76
+ klass = of.is_a?(::Class) ? of : registry.lookup(of)
77
+ return Nested.new(klass) if klass <= FieldStruct::Base
78
+ return klass if klass <= Types::Base
79
+
80
+ raise ::ArgumentError, "#{klass.inspect} is not a FieldStruct type (subclass FieldStruct::Types::Base)"
75
81
  end
76
82
  end
77
83
 
78
- # How many indexes an element error lists before counting the rest.
79
- # @return [::Integer]
80
- INDEXES_LISTED = 5
84
+ # @param value [::Object]
85
+ # @param of_type [::Class, FieldStruct::Types::Base, nil] element type (a class, or a Nested instance)
86
+ # @param element [::Hash{::Symbol=>::Object}, nil] options handed to each element's coerce
87
+ # @param max_items [::Integer, nil] how much of a lazy source an array of mirrors reads (FS-B169)
88
+ # @return [::Array<::Object>, nil] a new Array
89
+ # @raise [ArgumentError, TypeError, RangeError] when any element is refused (message names the indexes)
90
+ def coerce(value, of_type: nil, element: nil, max_items: nil, **)
91
+ coerce_with(value, of_type, element, max_items)
92
+ end
81
93
 
82
- # Name a set of element indexes for an error message: one reads
83
- # +element at index 2+, several +elements at index 2, 5+, and past
84
- # {INDEXES_LISTED} the rest are counted (+… and 7 more+). Indexes only,
85
- # never elements, so a message carries no value.
94
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
86
95
  #
87
- # @param indexes [::Array<::Integer>] ascending, at least one
88
- # @return [::String]
89
- def self.elements_at(indexes)
90
- return "element at index #{indexes.first}" if indexes.size == 1
91
-
92
- listed = indexes.first(INDEXES_LISTED).join(', ')
93
- rest = indexes.size - INDEXES_LISTED
94
- rest.positive? ? "elements at index #{listed} and #{rest} more" : "elements at index #{listed}"
96
+ # @param value [::Object]
97
+ # @param options [::Hash{::Symbol=>::Object}]
98
+ # @return [::Array<::Object>, nil]
99
+ # @api private
100
+ def coerce_positional(value, options)
101
+ coerce_with(value, options[:of_type], options[:element], options[:max_items])
95
102
  end
96
103
 
97
- # @param value [Object]
98
- # @return [Boolean] +true+ when +nil+ or empty
104
+ # @param value [::Object]
105
+ # @return [Boolean] true for nil and the empty Array
99
106
  def missing?(value)
100
- return true if value.nil?
101
- return true if value.respond_to?(:empty?) && value.empty?
102
-
103
- false
107
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
104
108
  end
105
109
 
106
- # @return [Class] the top-level +::Array+ class
110
+ # @return [::Class]
107
111
  def ruby_type
108
112
  ::Array
109
113
  end
110
114
 
115
+ # The field-level message for elements that break +element:+ restrictions.
116
+ #
117
+ # @param indexes [::Array<::Integer>] the offending 0-based indexes
118
+ # @return [::String]
119
+ def self.invalid_elements_message(indexes)
120
+ "#{elements_at(indexes)} #{indexes.size == 1 ? 'is' : 'are'} invalid"
121
+ end
122
+
111
123
  private
112
124
 
113
- # Coerce the elements after the first refused one, so the error names
114
- # every refused index, then raise the first element's error with them.
115
- # The same message reaches every coercion_policy, :raise included —
116
- # finishing the scan costs a refused array no more than an accepted one.
117
- #
118
- # @param value [::Array<Object, nil>] the input array
119
- # @param first [::Integer] the index of the first refused element
120
- # @param error [StandardError] what the element type raised for it
121
- # @param element_type [Types::Base] the element type instance
122
- # @param element [::Hash{::Symbol => Object, nil}, nil] element options
123
- # @return [void]
124
- # @raise [StandardError] +error+'s class, prefixed with the indexes
125
- def raise_refused!(value, first, error, element_type, element)
126
- indexes = [first]
127
- (first + 1).upto(value.size - 1) do |index|
128
- item = value[index]
129
- element ? element_type.coerce(item, **element) : element_type.coerce(item)
130
- rescue ArgumentError, ::TypeError, ::RangeError
131
- indexes << index
132
- end
133
- shown = indexes.size == 1 ? '' : " (index #{first} shown)"
134
- # Exception#exception keeps the class without calling a custom
135
- # initializer; the indexes, never the elements, are added. The cause
136
- # chain stays what it was, rather than gaining the unprefixed copy.
137
- raise error.exception("#{self.class.elements_at(indexes)}#{shown}: #{error.message}"), cause: error.cause
125
+ def coerce_with(value, of_type, element, max_items)
126
+ return nil if value.nil?
127
+ raise ::ArgumentError, 'array coerce requires of_type:' if of_type.nil?
128
+
129
+ type = of_type.is_a?(::Class) ? of_type.new : of_type
130
+ value = source_items(value, type, max_items) unless value.is_a?(::Array)
131
+ coerce_elements(value, type, element || NO_ELEMENT_OPTIONS)
138
132
  end
139
133
 
140
- # +of_type+ may be either a Types::Base subclass (the DSL form for
141
- # stock types like +:string+) or an already-built Types::Base
142
- # instance (the DSL form for parameterized types like
143
- # {Types::Nested}). Both produce a single cached instance per
144
- # configured element type.
145
- #
146
- # @param type_or_instance [Class<Types::Base>, Types::Base]
147
- # @return [Types::Base]
148
- def element_type_for(type_or_instance)
149
- return type_or_instance unless type_or_instance.is_a?(::Class)
134
+ # The items of a non-Array source for an array of mirrors: a loaded one whole, a lazy one up to one past
135
+ # +max_items:+ (FS-B169).
136
+ def source_items(value, type, max_items)
137
+ raise ::TypeError, "expected Array, got #{value.class}" unless type.is_a?(Nested) && type.struct_class.mirror?
138
+ return value.to_a if value.respond_to?(:loaded?) && value.loaded? == true
139
+ raise ::TypeError, "expected Array, got #{value.class}" unless value.respond_to?(:first)
140
+ raise Unbounded if max_items.nil?
141
+
142
+ value.first(max_items + 1)
143
+ end
144
+
145
+ # Builds the result by index and the failure list only on a failure, so a clean Array costs one new Array.
146
+ def coerce_elements(values, type, options)
147
+ failures = nil
148
+ positional = type.class.positional_coerce?
149
+ result = ::Array.new(values.size) do |index|
150
+ item = values[index]
151
+ next nil if item.nil?
152
+
153
+ begin
154
+ if positional then type.coerce_positional(item, options)
155
+ elsif options.empty? then type.coerce(item)
156
+ else type.coerce(item, **options)
157
+ end
158
+ rescue ::ArgumentError, ::TypeError, ::RangeError => e
159
+ (failures ||= []) << [index, e]
160
+ nil
161
+ end
162
+ end
163
+ raise_failures(failures) if failures
164
+ result
165
+ end
150
166
 
151
- @element_type_instances ||= {}
152
- @element_type_instances[type_or_instance] ||= type_or_instance.new
167
+ def raise_failures(failures)
168
+ indexes = failures.map(&:first)
169
+ first = failures.first.last
170
+ phrase = self.class.elements_at(indexes)
171
+ phrase += " (index #{indexes.first} shown)" if indexes.size > 1
172
+ error = first.class.new("#{phrase}: #{first.message}")
173
+ raise error, cause: first.cause
153
174
  end
154
175
  end
155
176
  end
@@ -1,161 +1,150 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FieldStruct
4
- # Namespace for the built-in coercion types ({Types::String}, {Types::Integer},
5
- # …) and the {Types::Base} contract that custom types implement.
4
+ # Namespace for the built-in types and the type contract.
6
5
  module Types
7
- # Abstract base for all FieldStruct type classes.
8
- #
9
- # Subclasses must implement {#coerce} and {#ruby_type}. They may override
10
- # {#missing?} when their notion of "missing" is broader than nil-only
11
- # (e.g. strings consider empty/whitespace missing, arrays consider empty
12
- # missing).
6
+ # The type contract. A custom type subclasses this, implements {#coerce} and {#ruby_type},
7
+ # and may override {#missing?}, +own_option_schema+ and +resolve_options+.
13
8
  class Base
14
- # Native per-field options this type understands, as a frozen Hash of
15
- # option-name (Symbol) → descriptor. Each descriptor is built by
16
- # {.option} and carries the accepted value classes, whether the option
17
- # is required at declaration time, and any Symbol presets it accepts.
18
- #
19
- # This merges {.own_option_schema} down the class chain so a subtype
20
- # inherits its parent's options for free (e.g. {Types::UUID} picks up
21
- # {Types::String}'s +format:+ / +enum:+). The merged result is frozen and
22
- # memoized per type class — a type's option vocabulary is fixed at load,
23
- # so this is computed once rather than on every field declaration.
24
- #
25
- # This is the single source of truth for both *validation* (the DSL
26
- # checks declared values against these descriptors) and *discoverability*
27
- # (an agent or human can ask a type what it accepts without reading
28
- # source). Options *not* listed here are treated as foreign and pass
29
- # through onto the Field untouched, available to downstream tooling.
30
- #
31
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
32
- def self.option_schema
33
- @option_schema ||= begin
34
- inherited = superclass.respond_to?(:option_schema) ? superclass.option_schema : {}
35
- inherited.merge(own_option_schema).freeze
9
+ class << self
10
+ # The options this class itself declares. Override in a subclass.
11
+ #
12
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}] option name to descriptor (see {.option})
13
+ def own_option_schema
14
+ {}
36
15
  end
37
- end
38
16
 
39
- # The options this type adds on top of its superclass's. Subclasses
40
- # override *this* (not {.option_schema}) to declare their native options;
41
- # the empty default means "adds nothing." {.option_schema} handles the
42
- # inheritance merge.
43
- #
44
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
45
- def self.own_option_schema
46
- {}
47
- end
17
+ # The superclass schema merged with {.own_option_schema}; own entries win,
18
+ # inherited keys keep their position.
19
+ #
20
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}] frozen and memoized per class
21
+ def option_schema
22
+ @option_schema ||= begin
23
+ inherited = superclass.respond_to?(:option_schema) ? superclass.option_schema : {}
24
+ inherited.merge(own_option_schema).freeze
25
+ end
26
+ end
48
27
 
49
- # Build a normalized descriptor for {.option_schema}.
50
- #
51
- # @param type [::Class, ::Array<::Class>] the Ruby class(es) a declared
52
- # value may be an instance of
53
- # @param required [Boolean] whether the option must be present at
54
- # field-declaration time
55
- # @param presets [::Array<::Symbol>] Symbol preset names the option also accepts
56
- # @return [::Hash{::Symbol => Object}] a frozen descriptor: +{ type:, required:, presets: }+
57
- def self.option(type:, required: false, presets: [])
58
- {type: ::Kernel.Array(type).freeze, required: required, presets: presets.to_a.freeze}.freeze
59
- end
28
+ # Builds an option descriptor.
29
+ #
30
+ # @param type [::Class, ::Array<::Class>] the classes a value may be an instance of
31
+ # @param required [Boolean]
32
+ # @param presets [::Array<::Symbol>] preset names the option accepts
33
+ # @return [::Hash{::Symbol=>::Object}] frozen +{type:, required:, presets:}+
34
+ def option(type:, required: false, presets: [])
35
+ { type: [type].flatten.freeze, required: required, presets: presets.dup.freeze }.freeze
36
+ end
60
37
 
61
- # Resolve symbolic preset references on the per-field options hash
62
- # at field-declaration time. Default implementation passes options
63
- # through unchanged; concrete types override to interpret their
64
- # own options (e.g. +format: :iso8601+ → strftime string).
65
- #
66
- # @param options [::Hash{::Symbol => Object, nil}] the per-field options hash, as written by the user
67
- # @return [::Hash{::Symbol => Object, nil}] possibly-modified options to store on the Field
68
- def self.resolve_options(options)
69
- options
70
- end
38
+ # Declaration-time hook: turn preset Symbols into values and reject bad ones. A type may also declare
39
+ # +registry:+ and +field_name:+ keywords to receive the field's registry chain and name.
40
+ #
41
+ # @param options [::Hash{::Symbol=>::Object}]
42
+ # @return [::Hash{::Symbol=>::Object}]
43
+ def resolve_options(options, **)
44
+ options
45
+ end
71
46
 
72
- # Resolve a declared +format:+ into the form coercion and rendering use.
73
- #
74
- # Declared options are kept exactly as the user wrote them — see
75
- # {TimeFormatResolver} for why — so a Symbol preset name has to be
76
- # expanded somewhere, and the type owning the preset table is the only
77
- # thing that can do it. This default serves types with no preset table:
78
- # a String passes through, a Symbol is refused.
79
- #
80
- # @param format [::String, ::Symbol, nil] the format as declared
81
- # @return [::String, nil]
82
- # @raise [ArgumentError] when given a Symbol and the type has no presets
83
- def self.resolve_format(format)
84
- return format if format.nil? || format.is_a?(::String)
47
+ # Builds the instance a Field uses, from the resolved options.
48
+ #
49
+ # @param options [::Hash{::Symbol=>::Object}] the options after {.resolve_options} and the +format:+ prefill
50
+ # @return [Array(FieldStruct::Types::Base, ::Hash{::Symbol=>::Object})] the instance and the options to store on the Field
51
+ # @api private
52
+ def instantiate(options)
53
+ [new, options]
54
+ end
55
+
56
+ # @param key [::Symbol] a schema option marked +required: true+ that a field left out
57
+ # @return [::String] the declaration error message
58
+ # @api private
59
+ def required_option_message(key)
60
+ "#{key}: is required for #{short_name} fields"
61
+ end
85
62
 
86
- raise ArgumentError, "#{name || "this type"} has no format presets; got #{format.inspect}"
63
+ # Resolves a +format:+ value for types without presets.
64
+ #
65
+ # @param format [::String, nil]
66
+ # @return [::String, nil]
67
+ # @raise [ArgumentError] for anything but nil or a String
68
+ def resolve_format(format)
69
+ return format if format.nil? || format.is_a?(::String)
70
+
71
+ raise ::ArgumentError, "#{short_name} has no format presets; got #{format.inspect}"
72
+ end
73
+
74
+ # @return [::String] the last segment of the class name, or +AnonymousType+
75
+ # @api private
76
+ def short_name
77
+ name ? name.split('::').last : 'AnonymousType'
78
+ end
79
+
80
+ # Internal: whether callers may use {#coerce_positional} instead of {#coerce}. True only when
81
+ # +coerce_positional+ is defined at or below +coerce+, so a subclass that overrides +coerce+ alone, or any
82
+ # custom type, still gets every option as keywords.
83
+ #
84
+ # @return [Boolean]
85
+ # @api private
86
+ def positional_coerce?
87
+ instance_method(:coerce_positional).owner <= instance_method(:coerce).owner
88
+ end
87
89
  end
88
90
 
89
- # Coerce an input value into the type's domain.
90
- #
91
- # The contract here is intentionally loose — subclasses override with
92
- # explicit kwargs for the options they consume (e.g. +format:+ for
93
- # Date, +round:+ for Float, +of_type:+ for Array), plus a trailing
94
- # +**+ catch-all so a call site that splats +field.options+ can pass
95
- # keys that some types ignore. See each subclass's +coerce+ for the
96
- # exact accepted options.
91
+ # Coerces a value; +nil+ must give +nil+. A failure raises ArgumentError, TypeError or RangeError.
92
+ # Implementations declare the options they consume as keywords and end with a +**+ catch-all.
97
93
  #
98
- # @param value [Object] raw input — each subclass narrows this to
99
- # the inputs it actually accepts
100
- # @return [Object] the coerced value
101
- # @raise [NotImplementedError] always, unless overridden by a subclass
102
- def coerce(value, **)
94
+ # @param _value [::Object]
95
+ # @return [::Object]
96
+ # @raise [NotImplementedError] unless overridden
97
+ def coerce(_value, **)
103
98
  raise NotImplementedError, "#{self.class} must implement #coerce"
104
99
  end
105
100
 
106
- # Whether the given value should be treated as "missing" for the purpose
107
- # of presence checks. The default is nil-only; subclasses override for
108
- # emptier notions.
109
- #
110
- # @param value [Object]
111
- # @return [Boolean]
101
+ # Internal: {#coerce} with the options as one Hash. Built-ins answer it without a keyword splat;
102
+ # here it delegates, so any type works (see {.positional_coerce?}).
103
+ #
104
+ # @param value [::Object]
105
+ # @param options [::Hash{::Symbol=>::Object}]
106
+ # @return [::Object]
107
+ # @api private
108
+ def coerce_positional(value, options)
109
+ options.empty? ? coerce(value) : coerce(value, **options)
110
+ end
111
+
112
+ # @param value [::Object] an already coerced value
113
+ # @return [Boolean] whether a required field must reject it
112
114
  def missing?(value)
113
115
  value.nil?
114
116
  end
115
117
 
116
- # The native Ruby class a coerced value will be an instance of.
117
- # Used by the (deferred) RBS generator and for introspection.
118
- #
119
- # @return [Class]
120
- # @raise [NotImplementedError] always, unless overridden by a subclass
118
+ # @return [::Class, ::Array<::Class>] the Ruby class(es) of coerced values
119
+ # @raise [NotImplementedError] unless overridden
121
120
  def ruby_type
122
121
  raise NotImplementedError, "#{self.class} must implement #ruby_type"
123
122
  end
124
123
 
125
- # The RBS type expression {FieldStruct::RBS} emits for fields of this
126
- # type, or +nil+ (the default) to derive one from {#ruby_type}. Override
127
- # in a custom type whose values {#ruby_type} can't describe on its own —
128
- # typically a generic class, which RBS needs type arguments for:
129
- #
130
- # def ruby_type = ::Hash
131
- # def rbs_type = '::Hash[::Symbol, ::String]'
132
- #
133
- # Without it a bare generic +ruby_type+ is emitted with +untyped+
134
- # arguments (+::Hash[untyped, untyped]+). A field's own +rbs_type:+
135
- # option wins over this. Fully qualify constants (+::Hash+, not
136
- # +Hash+): the RBS is emitted inside the struct's module nesting.
137
- #
138
- # @return [::String, nil]
124
+ # @return [::String, nil] an RBS type to use instead of the derived one
139
125
  def rbs_type
140
126
  nil
141
127
  end
142
128
 
143
- # Concise type-instance representation. The default shows just the
144
- # type-class name (e.g. +#<FieldStruct::Types::String>+). Subclasses
145
- # that carry parameter state (Nested, Union, …) override to surface
146
- # what they wrap.
147
- #
148
129
  # @return [::String]
149
130
  def inspect
150
- full = self.class.name || 'AnonymousType'
151
- prefixed = full.sub(/\AFieldStruct\b/, FieldStruct.inspect_namespace)
152
- "#<#{prefixed}>"
131
+ name = self.class.name
132
+ name = name ? name.sub(/\AFieldStruct/, FieldStruct.inspect_namespace) : 'AnonymousType'
133
+ "#<#{name}>"
153
134
  end
154
135
 
155
- # @param pp [Object] a PP-shaped sink (responds to +#text+)
136
+ # @param printer [PP]
156
137
  # @return [void]
157
- def pretty_print(pp)
158
- pp.text(inspect)
138
+ def pretty_print(printer)
139
+ printer.text(inspect)
140
+ end
141
+
142
+ private
143
+
144
+ # "a Float" / "an Integer": the input's class with its article. Only ever names the class.
145
+ def class_phrase(value)
146
+ name = value.class.to_s
147
+ "#{name.match?(/\A[AEIOU]/) ? 'an' : 'a'} #{name}"
159
148
  end
160
149
  end
161
150
  end