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,162 +1,53 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'date'
4
- require_relative 'base'
5
-
6
3
  module FieldStruct
7
4
  module Types
8
- # DateTime type. Returns a +DateTime+ as-is, builds one from a +Date+ or
9
- # +Time+'s components, reads a String via +DateTime.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 DateTime < 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] field-level strftime/strptime format; +nil+
30
- # leaves the type using ISO-8601 in/out
31
- def self.default_format
32
- nil
33
- end
34
-
35
- # Named presets for the +format:+ option.
36
- #
37
- # +:iso8601+ is an {Rfc3339Format} rather than a strftime String: +%z+
38
- # renders +\+0000+, which RFC 3339 rejects, and no strftime string can
39
- # express optional fractional seconds. The interchange and display
40
- # presets stay strftime-based.
41
- #
42
- # @return [Hash{::Symbol=>Object}]
43
- def self.presets
44
- {
45
- iso8601: Rfc3339Format.timestamp,
46
- rfc2822: '%a, %d %b %Y %H:%M:%S %z',
47
- db: '%Y-%m-%d %H:%M:%S'
48
- }
49
- end
50
-
51
- # Validate a Symbol +format:+ preset (see {.presets}) and a +zone:+
52
- # (see {ZoneOption}) at field-declaration time.
53
- #
54
- # @param options [::Hash{::Symbol => Object, nil}] the per-field options
55
- # @return [::Hash{::Symbol => Object, nil}] the options, unchanged
56
- # @raise [ArgumentError] on an unknown preset or an unreadable +zone:+
57
- def self.resolve_options(options)
58
- ZoneOption.validate!('DateTime', TimeFormatResolver.call(options, presets))
59
- end
60
-
61
- # Resolve a declared +format:+ (a Symbol preset name or a strftime
62
- # String) into the String that {#coerce} and JSON rendering actually
63
- # use. Declarations are stored exactly as written, so this is where a
64
- # preset name becomes usable. See {TimeFormatResolver}.
65
- #
66
- # @param format [::String, ::Symbol, nil] the format as declared
67
- # @return [::String, nil] +nil+ when the field declares no format
68
- # @raise [ArgumentError] when a Symbol names no preset in {.presets}
69
- def self.resolve_format(format)
70
- # Skip building the presets Hash for the common, undeclared case.
71
- return format if format.nil? || format.is_a?(::String)
72
-
73
- TimeFormatResolver.resolve(format, presets)
74
- end
75
-
76
- # Dispatch is on explicit stdlib classes, never on a +respond_to?+ probe
77
- # against the value: ActiveSupport defines +String#to_datetime+, so a
78
- # probe that is false on plain Ruby is TRUE under Rails.
79
- # +DateTime.parse+ and +DateTime.strptime+ are not redefined by
80
- # ActiveSupport. See {Types::Time#coerce} for why cross-class conversion
81
- # is built from components rather than +to_datetime+.
82
- #
83
- # @param value [::String, ::DateTime, ::Date, ::Time, nil] +nil+ → +nil+;
84
- # a String is read through +strptime+ when a +format:+ is set and
85
- # +DateTime.parse+ otherwise; a +DateTime+ passes through; a +Date+
86
- # becomes midnight and a +Time+ (including ActiveSupport's
87
- # TimeWithZone) keeps its instant and offset. Anything else is refused.
88
- # @param format [::String, nil] strptime/strftime format; +nil+ uses
89
- # {.default_format} (which itself defaults to +nil+ = ISO-8601 path)
90
- # @param zone [::String, nil] +"UTC"+, +"±HH:MM"+ or an IANA name: the offset for a
91
- # String that names none, and for a +Date+'s midnight. Input carrying
92
- # its own offset keeps it. +nil+ means UTC. See {ZoneOption}.
93
- # @return [::DateTime, nil]
94
- # @raise [ArgumentError] when a String cannot be parsed, or the value is
95
- # not a String or a temporal object
96
- def coerce(value, format: self.class.default_format, zone: nil, **)
97
- return nil if value.nil?
98
-
99
- fmt = self.class.resolve_format(format)
100
-
101
- case value
102
- when ::String then parse_string(value, fmt, zone)
103
- # ::DateTime before ::Date — DateTime is a subclass of Date.
104
- when ::DateTime then value
105
- when ::Date
106
- return datetime_from_time(ZoneOption.midnight(value, zone)) if zone
5
+ # An instant as a DateTime. A zone-less string lands at offset 0, or in +zone:+ when declared.
6
+ class DateTime < Temporal
7
+ # Named formats the +format:+ option accepts (strptime Strings, or the RFC 3339 reader).
8
+ # @return [::Hash{::Symbol=>::Object}]
9
+ PRESETS = Time::PRESETS
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
- ::DateTime.new(value.year, value.mon, value.mday)
109
- # ActiveSupport::TimeWithZone matches here too (AS overrides Time.===)
110
- # and answers every reader this uses.
111
- when ::Time then datetime_from_time(value)
112
- else
113
- # The class, never the value — see Types::Date#coerce.
114
- raise ArgumentError, "expected a String, Date, DateTime or Time, got #{value.class}"
17
+ # @return [true]
18
+ def zoned?
19
+ true
115
20
  end
116
21
  end
117
22
 
118
- # @return [Class] the top-level +::DateTime+ class
23
+ # @return [::Class]
119
24
  def ruby_type
120
25
  ::DateTime
121
26
  end
122
27
 
123
28
  private
124
29
 
125
- # @param value [::String] the raw string
126
- # @param format [::String, nil] strptime format, when the field declares one
127
- # @param zone [::String, nil] the field's +zone:+, if declared
128
- # @return [::DateTime]
129
- # @raise [ArgumentError] when the string cannot be read
130
- def parse_string(value, format, zone)
131
- # Validated first, then handed to the stdlib parser: the checks decide
132
- # what is ACCEPTABLE, the stdlib still decides what the value IS, so
133
- # the two can't drift apart. See {TemporalParser} for the three rules.
134
- if format.is_a?(Rfc3339Format)
135
- parts = format.parse(value)
136
- return ::DateTime.new(parts[:year], parts[:mon], parts[:mday], parts[:hour], parts[:min],
137
- parts[:sec] + parts[:sec_fraction], ::Kernel.Rational(parts[:offset], 86_400))
138
- end
30
+ def epoch_time(seconds)
31
+ ::Time.at(seconds, in: 0)
32
+ end
139
33
 
140
- if format
141
- parts = TemporalParser.strptime_parts(value, format)
142
- return datetime_from_time(ZoneOption.time_at(value, format, zone, parts)) if zone && ZoneOption.zoneless?(parts)
34
+ def assemble(components, zone)
35
+ from_time(time_from(components, zone))
36
+ end
143
37
 
144
- return ::DateTime.strptime(value, format)
145
- end
38
+ def from_datetime(value)
39
+ value
40
+ end
146
41
 
147
- parts = TemporalParser.parse_parts(value)
148
- return datetime_from_time(ZoneOption.time_at(value, nil, zone, parts)) if zone && ZoneOption.zoneless?(parts)
42
+ def from_date(value, zone)
43
+ return from_time(zone.start_of_day(value.year, value.mon, value.mday)) if zone
149
44
 
150
- ::DateTime.parse(value)
45
+ ::DateTime.new(value.year, value.mon, value.mday, 0, 0, 0, 0)
151
46
  end
152
47
 
153
- # @param value [::Time] the value to convert
154
- # @return [::DateTime] the same instant, at the same offset, sub-second
155
- # precision preserved
156
- def datetime_from_time(value)
157
- ::DateTime.new(value.year, value.mon, value.mday, value.hour, value.min,
158
- value.sec + ::Kernel.Rational(value.nsec, 1_000_000_000),
159
- ::Kernel.Rational(value.utc_offset, 86_400))
48
+ def from_time(value)
49
+ ::DateTime.new(value.year, value.mon, value.mday, value.hour, value.min, value.sec + value.subsec,
50
+ Rational(value.utc_offset, 86_400))
160
51
  end
161
52
  end
162
53
  end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Types
5
+ # Declaration-time validation of an array's +element:+ Hash against the element type's own schema.
6
+ module ElementOptions
7
+ # @param element_class [::Class] the element type's class
8
+ # @param element [::Hash, nil] the declared +element:+ options
9
+ # @param registry [FieldStruct::Registry]
10
+ # @param field_name [::Symbol]
11
+ # @param kind [::String] the field's type name in messages: +array+ or +hash+
12
+ # @return [::Hash, nil] the resolved options, frozen; +nil+ when empty or absent
13
+ # @raise [ArgumentError] with an +in element: of array field :name,+ prefix
14
+ def self.call(element_class, element, registry:, field_name:, kind: 'array')
15
+ return nil if element.nil? || element.empty?
16
+
17
+ prefix = "in element: of #{kind} field #{field_name.inspect}, "
18
+ refuse_composite(element_class, prefix)
19
+ element.each_key { |key| check_key(element_class, key, prefix) }
20
+ resolved = OptionChecker.element(element_class, element, registry: registry, field_name: field_name)
21
+ resolved.freeze
22
+ rescue ::ArgumentError => e
23
+ raise if e.message.start_with?(prefix)
24
+
25
+ raise ::ArgumentError, "#{prefix}#{e.message}", cause: nil
26
+ end
27
+
28
+ def self.refuse_composite(element_class, prefix)
29
+ return unless element_class <= Types::Array || element_class <= Types::Hash || element_class <= Types::Union
30
+
31
+ raise ::ArgumentError, "#{prefix}element options are not supported for #{element_class.short_name} elements"
32
+ end
33
+
34
+ def self.check_key(element_class, key, prefix)
35
+ if FieldBuilder::UNIVERSAL_OPTIONS.include?(key)
36
+ raise ::ArgumentError, "#{prefix}#{key}: is a field option, not an element option. Declare it on the field itself."
37
+ end
38
+
39
+ schema = element_class.option_schema
40
+ return if schema.key?(key)
41
+
42
+ name = element_class.short_name
43
+ article = name.match?(/\A[AEIOU]/) ? 'an' : 'a'
44
+ accepts = schema.empty? ? "#{name} accepts no options." : "#{name} accepts: #{schema.keys.join(', ')}."
45
+ raise ::ArgumentError, "#{prefix}#{key}: is not #{article} #{name} option. #{accepts}"
46
+ end
47
+
48
+ private_class_method :refuse_composite, :check_key
49
+ end
50
+ end
51
+ end
@@ -1,48 +1,37 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'string'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # Email type — a {Types::String} that pre-fills the field's +format:+
8
- # option with a pragmatic email pattern. Same shape as
9
- # {Types::UUID} / {Types::URL}: bad-format input is a validation
10
- # error, not a coercion failure.
11
- #
12
- # The default pattern is deliberately not RFC 5322 strict — those
13
- # regexes are unwieldy and reject real-world addresses. It checks
14
- # +local@domain.tld+ shape with no internal whitespace or extra +@+
15
- # characters; users can override via +format: /.../+ for stricter
16
- # rules.
17
- class Email < FieldStruct::Types::String
18
- # Inherits +format:+ / +enum:+ from {Types::String}, advertising the
19
- # +:format+ presets this subtype resolves (see {.presets}).
20
- #
21
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
22
- def self.own_option_schema
23
- {format: option(type: [::Regexp, ::Symbol], presets: presets.keys)}
24
- end
5
+ # A String that must look like an email address.
6
+ class Email < String
7
+ # One DNS label, as a pattern source.
8
+ # @return [::String]
9
+ LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?'
10
+ # Named formats the +format:+ option accepts.
11
+ # @return [::Hash{::Symbol=>::Regexp}]
12
+ PRESETS = {
13
+ permissive: /\A[^@\s]+@[^@\s]+\z/,
14
+ default: /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/,
15
+ strict: /\A[\w.+-]+@#{LABEL}(?:\.#{LABEL})+\z/
16
+ }.freeze
25
17
 
26
- # @return [Regexp] pragmatic +local@domain.tld+ shape, no internal
27
- # whitespace or extra +@+; deliberately not RFC 5322 strict.
28
- # Override per-field via +format:+ (Regexp or Symbol preset).
29
- def self.default_format
30
- /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/
31
- end
18
+ extend FormatPresets
32
19
 
33
- # @return [Hash{::Symbol=>Regexp}] named presets for +format:+
34
- def self.presets
35
- {
36
- permissive: /\A[^@\s]+@[^@\s]+\z/,
37
- default: default_format,
38
- strict: /\A[\w.+-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+\z/
39
- }
40
- end
20
+ class << self
21
+ # @return [::Hash{::Symbol=>::Regexp}] preset name to pattern
22
+ def presets
23
+ PRESETS
24
+ end
25
+
26
+ # @return [::Symbol] the preset used when a field declares no +format:+
27
+ def fallback_preset
28
+ :default
29
+ end
41
30
 
42
- # Resolve a Symbol +format:+ preset (see {.presets}) to its Regexp at
43
- # field-declaration time; a user-supplied Regexp passes through.
44
- def self.resolve_options(options)
45
- PresetResolver.call(options, :format, presets, label: ':email format')
31
+ # @return [::String] how preset errors name this type
32
+ def preset_caption
33
+ ':email'
34
+ end
46
35
  end
47
36
  end
48
37
  end
@@ -1,79 +1,81 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'base'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # Float type. Coerces via +Kernel#Float+, which parses numeric strings
8
- # strictly and rejects anything non-numeric. Strings are base 10, as for
9
- # {Types::Integer}: a hex string like "0x1A", which +Kernel#Float+ would
10
- # read as 26.0, is refused.
5
+ # Floating point numbers. Refuses NaN, infinities and hex strings; +round:+ rounds half up.
11
6
  class Float < Base
12
- # A string +Kernel#Float+ would read as hex: optional whitespace and
13
- # sign, then +0x+. (Binary and octal prefixes it already refuses.)
7
+ # Matches a hexadecimal-looking string, which Float() would accept.
14
8
  # @return [::Regexp]
15
9
  HEX_PREFIX = /\A\s*[+-]?0x/i
16
- # Native options: a +round:+ Integer precision and an +in:+ Array or
17
- # Range of allowed values.
18
- #
19
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
20
- def self.own_option_schema
21
- {
22
- round: option(type: [::Integer]),
23
- in: option(type: [::Array, ::Range])
24
- }
25
- end
10
+ # Matches a number written with a trailing dot, such as +"5."+.
11
+ # @return [::Regexp]
12
+ TRAILING_DOT = /\A(\s*[+-]?\d[\d_]*)\.(\s*)\z/
26
13
 
27
- # @return [::Integer, nil] field-level rounding precision; +nil+ disables.
28
- def self.default_round
29
- nil
30
- end
14
+ class << self
15
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}]
16
+ def own_option_schema
17
+ { round: option(type: ::Integer), in: option(type: [::Array, ::Range]) }
18
+ end
31
19
 
32
- # @param value [Numeric, ::String, nil] +nil+ → +nil+; everything
33
- # else flows through +Kernel#Float+ — strict on string parsing,
34
- # rejects non-numeric strings, Symbols, Booleans, Arrays, and
35
- # hex strings ("0x1A").
36
- # @param round [::Integer, nil] decimal places, rounding half up (ties
37
- # away from zero); +nil+ leaves the value unrounded. The result is a
38
- # Float even at +round: 0+.
39
- # @return [::Float, nil] +nil+ for +nil+ input, otherwise the parsed float
40
- # @raise [ArgumentError, TypeError] when the value cannot be coerced
41
- # (a String that is not a number, a Complex), or coerces to NaN or
42
- # ±Infinity (including a String like "1e400")
43
- def coerce(value, round: self.class.default_round, **)
44
- return nil if value.nil?
20
+ # Class-wide rounding places used when a field declares no +round:+.
21
+ #
22
+ # @return [::Integer, nil]
23
+ def default_round
24
+ nil
25
+ end
26
+ end
45
27
 
46
- result = value.is_a?(::Float) ? value : parse(value)
47
- # The class, never the value — see Types::Time#coerce.
48
- raise ArgumentError, "Float fields expect a finite number, got a non-finite #{value.class}" unless result.finite?
28
+ # @param value [::Object]
29
+ # @param round [::Integer, nil] decimal places, half up; may be zero or negative
30
+ # @return [::Float, nil]
31
+ # @raise [ArgumentError, TypeError] when the value cannot be read
32
+ def coerce(value, round: nil, **)
33
+ coerce_with(value, round)
34
+ end
49
35
 
50
- # Float#round returns an Integer at round: 0; .to_f keeps the
51
- # field's type. half: :up pins ties away from zero.
52
- round ? result.round(round, half: :up).to_f : result
36
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
37
+ #
38
+ # @param value [::Object]
39
+ # @param options [::Hash{::Symbol=>::Object}]
40
+ # @return [::Float, nil]
41
+ # @api private
42
+ def coerce_positional(value, options)
43
+ coerce_with(value, options[:round])
53
44
  end
54
45
 
55
- # @return [Class] the top-level +::Float+ class
46
+ # @return [::Class]
56
47
  def ruby_type
57
48
  ::Float
58
49
  end
59
50
 
60
51
  private
61
52
 
62
- # @param value [Object] a non-Float value
63
- # @return [::Float]
64
- # @raise [ArgumentError] when it is a hex string or +Kernel#Float+
65
- # refuses it; the message names the class, never the value
66
- # (Kernel's own message echoes it)
67
- def parse(value)
68
- if value.is_a?(::String) && HEX_PREFIX.match?(value)
69
- raise ArgumentError, 'Float fields expect a base-10 number, got a String that is not one'
70
- end
53
+ def coerce_with(value, round)
54
+ return nil if value.nil?
71
55
 
72
- begin
73
- ::Kernel.Float(value)
74
- rescue ::ArgumentError, ::RangeError
75
- raise ArgumentError, "Float fields could not read a #{value.class} as a number", cause: nil
76
- end
56
+ number = to_float(value)
57
+ places = round || self.class.default_round
58
+ places ? number.round(places, half: :up).to_f : number
59
+ end
60
+
61
+ def to_float(value)
62
+ number = value.is_a?(::String) ? from_string(value) : from_other(value)
63
+ return number if number.finite?
64
+
65
+ raise ::ArgumentError, "Float fields expect a finite number, got a non-finite #{value.class}"
66
+ end
67
+
68
+ def from_string(text)
69
+ raise ::ArgumentError, 'Float fields expect a base-10 number, got a String that is not one' if text.match?(HEX_PREFIX)
70
+
71
+ Float(text.sub(TRAILING_DOT) { "#{Regexp.last_match(1)}.0#{Regexp.last_match(2)}" }, exception: false) ||
72
+ raise(::ArgumentError, 'Float fields could not read a String as a number')
73
+ end
74
+
75
+ def from_other(value)
76
+ Float(value)
77
+ rescue ::RangeError, ::ArgumentError
78
+ raise ::ArgumentError, "Float fields could not read #{class_phrase(value)} as a number", cause: nil
77
79
  end
78
80
  end
79
81
  end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Types
5
+ # Class-level behaviour shared by the string types that validate against a Regexp by default
6
+ # (+uuid+, +url+, +email+). The extending class defines +presets+, +fallback_preset+ and +preset_caption+.
7
+ module FormatPresets
8
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}] the string schema, with +format:+ listing this type's presets
9
+ def own_option_schema
10
+ { format: option(type: [::Regexp, ::Symbol], presets: presets.keys) }
11
+ end
12
+
13
+ # Replaces a +format:+ preset Symbol by its Regexp.
14
+ #
15
+ # @param options [::Hash{::Symbol=>::Object}]
16
+ # @return [::Hash{::Symbol=>::Object}]
17
+ # @raise [ArgumentError] for an unknown preset name
18
+ def resolve_options(options, **)
19
+ PresetResolver.call(options, :format, presets, label: "#{preset_caption} format")
20
+ end
21
+
22
+ # The Regexp written into a field's options when it declares no +format:+.
23
+ #
24
+ # @return [::Regexp]
25
+ def default_format
26
+ presets.fetch(fallback_preset)
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Types
5
+ # A map from String keys to values of one type (FS-B79a). A refused key or value fails the whole map; no message names a key.
6
+ class Hash < Base
7
+ NO_VALUE_OPTIONS = {}.freeze
8
+ private_constant :NO_VALUE_OPTIONS
9
+
10
+ class << self
11
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}]
12
+ def own_option_schema
13
+ {
14
+ of: option(type: [::Symbol, ::String, ::Class], required: true),
15
+ element: option(type: ::Hash)
16
+ }
17
+ end
18
+
19
+ # @param _key [::Symbol]
20
+ # @return [::String]
21
+ def required_option_message(_key)
22
+ 'hash field requires an `of:` option naming the value type'
23
+ end
24
+
25
+ # Replaces +of:+ by +of_type:+ (a type class, or a Nested instance for a struct) and validates +element:+.
26
+ #
27
+ # @param options [::Hash{::Symbol=>::Object}]
28
+ # @param registry [FieldStruct::Registry]
29
+ # @param field_name [::Symbol]
30
+ # @return [::Hash{::Symbol=>::Object}]
31
+ # @raise [ArgumentError, KeyError] for an unknown value type or bad value options
32
+ def resolve_options(options, registry:, field_name:)
33
+ of_type = Types::Array.send(:element_type_for, options[:of], registry)
34
+ resolved = { of_type: of_type }.merge(options.except(:of, :element))
35
+ element = ElementOptions.call(Types::Array.element_class(of_type), options[:element],
36
+ registry: registry, field_name: field_name, kind: 'hash')
37
+ element ? resolved.merge(element: element) : resolved
38
+ end
39
+
40
+ # The field-level message for values that break +element:+ restrictions; it names no key.
41
+ #
42
+ # @param count [::Integer] how many values failed
43
+ # @return [::String]
44
+ def invalid_entries_message(count)
45
+ count == 1 ? '1 entry is invalid' : "#{count} entries are invalid"
46
+ end
47
+ end
48
+
49
+ # @param value [::Object]
50
+ # @param of_type [::Class, FieldStruct::Types::Base, nil] the value type (a class, or a Nested instance)
51
+ # @param element [::Hash{::Symbol=>::Object}, nil] options handed to each value's coerce
52
+ # @return [::Hash{::String=>::Object}, nil] a new Hash with String keys
53
+ # @raise [ArgumentError, TypeError, RangeError] when a key or any value is refused (the message names no key)
54
+ def coerce(value, of_type: nil, element: nil, **)
55
+ coerce_with(value, of_type, element)
56
+ end
57
+
58
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
59
+ #
60
+ # @param value [::Object]
61
+ # @param options [::Hash{::Symbol=>::Object}]
62
+ # @return [::Hash{::String=>::Object}, nil]
63
+ # @api private
64
+ def coerce_positional(value, options)
65
+ coerce_with(value, options[:of_type], options[:element])
66
+ end
67
+
68
+ # @param value [::Object]
69
+ # @return [Boolean] true for nil and the empty Hash
70
+ def missing?(value)
71
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
72
+ end
73
+
74
+ # @return [::Class]
75
+ def ruby_type
76
+ ::Hash
77
+ end
78
+
79
+ private
80
+
81
+ # @param value [::Object]
82
+ # @param of_type [::Class, FieldStruct::Types::Base, nil]
83
+ # @param element [::Hash{::Symbol=>::Object}, nil]
84
+ # @return [::Hash{::String=>::Object}, nil]
85
+ def coerce_with(value, of_type, element)
86
+ return nil if value.nil?
87
+ raise ::ArgumentError, 'hash coerce requires of_type:' if of_type.nil?
88
+ raise ::TypeError, "expected Hash, got #{value.class}" unless value.is_a?(::Hash)
89
+
90
+ coerce_entries(value, of_type.is_a?(::Class) ? of_type.new : of_type, element || NO_VALUE_OPTIONS)
91
+ end
92
+
93
+ # @param entries [::Hash{::Object=>::Object}]
94
+ # @param type [FieldStruct::Types::Base]
95
+ # @param options [::Hash{::Symbol=>::Object}]
96
+ # @return [::Hash{::String=>::Object}]
97
+ def coerce_entries(entries, type, options)
98
+ failures = nil
99
+ positional = type.class.positional_coerce?
100
+ result = {}
101
+ entries.each do |key, item|
102
+ name = string_key(key)
103
+ result[name] = begin
104
+ item.nil? ? nil : coerce_value(type, item, options, positional)
105
+ rescue ::ArgumentError, ::TypeError, ::RangeError => e
106
+ (failures ||= []) << e
107
+ nil
108
+ end
109
+ end
110
+ raise_failures(failures) if failures
111
+ result
112
+ end
113
+
114
+ # @param key [::Object]
115
+ # @return [::String]
116
+ def string_key(key)
117
+ return key if key.is_a?(::String)
118
+ return key.to_s if key.is_a?(::Symbol)
119
+
120
+ raise ::TypeError, "hash keys must be Strings or Symbols, got #{key.class}"
121
+ end
122
+
123
+ # @param type [FieldStruct::Types::Base]
124
+ # @param item [::Object]
125
+ # @param options [::Hash{::Symbol=>::Object}]
126
+ # @param positional [Boolean]
127
+ # @return [::Object]
128
+ def coerce_value(type, item, options, positional)
129
+ if positional then type.coerce_positional(item, options)
130
+ elsif options.empty? then type.coerce(item)
131
+ else type.coerce(item, **options)
132
+ end
133
+ end
134
+
135
+ # @param failures [::Array<::Exception>]
136
+ # @return [void]
137
+ def raise_failures(failures)
138
+ first = failures.first
139
+ phrase = failures.size == 1 ? 'value of 1 entry' : "values of #{failures.size} entries (first shown)"
140
+ raise first.class.new("#{phrase}: #{first.message}"), cause: first.cause
141
+ end
142
+ end
143
+ end
144
+ end