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,77 +1,81 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'bigdecimal'
4
- require_relative 'base'
5
-
6
3
  module FieldStruct
7
4
  module Types
8
- # BigDecimal type. Accepts a {::BigDecimal}, +Integer+, +Float+, or a
9
- # numeric string. Float input is converted with +Float::DIG+ precision
10
- # to avoid the bare +BigDecimal(Float)+ "can't omit precision" error.
5
+ # Exact decimals. Floats are read with 15 significant digits; +round:+ rounds half up.
11
6
  class BigDecimal < Base
12
- # Native options: a +round:+ Integer precision and an +in:+ Array or
13
- # Range of allowed values.
14
- #
15
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
16
- def self.own_option_schema
17
- {
18
- round: option(type: [::Integer]),
19
- in: option(type: [::Array, ::Range])
20
- }
21
- end
7
+ class << self
8
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}]
9
+ def own_option_schema
10
+ { round: option(type: ::Integer), in: option(type: [::Array, ::Range]), json: option(type: ::Symbol) }
11
+ end
22
12
 
23
- # @return [::Integer, nil] the field-level rounding precision, or +nil+
24
- # for no rounding. Subclasses override.
25
- def self.default_round
26
- nil
13
+ # How +to_json+ writes this type's values when a field declares no +json:+ (FS-B106a). A subclass that must
14
+ # survive JavaScript's float parsing answers +:string+.
15
+ #
16
+ # @return [::Symbol] +:number+ or +:string+
17
+ def json_default
18
+ :number
19
+ end
20
+
21
+ # Class-wide rounding places used when a field declares no +round:+.
22
+ #
23
+ # @return [::Integer, nil]
24
+ def default_round
25
+ nil
26
+ end
27
27
  end
28
28
 
29
- # @param value [::BigDecimal, Numeric, ::String, nil] +nil+ → +nil+;
30
- # a +BigDecimal+ passes through; +Float+ uses +Float::DIG+
31
- # precision; everything else goes through
32
- # +Kernel.BigDecimal(value.to_s)+ — non-numeric strings raise
33
- # ArgumentError.
34
- # @param round [::Integer, nil] decimal places, rounding half up (ties
35
- # away from zero) whatever the global +BigDecimal.mode+; +nil+ leaves
36
- # the value unrounded. The result is a BigDecimal even at +round: 0+.
29
+ # @param value [::Object]
30
+ # @param round [::Integer, nil] decimal places, half up whatever +BigDecimal.mode+ says
37
31
  # @return [::BigDecimal, nil]
38
- # @raise [ArgumentError] when a value's string form cannot be parsed
39
- # (e.g. a non-numeric String, or a Rational's "1/3"), or the value
40
- # is NaN or ±Infinity (as a Float, a BigDecimal, or a String like "NaN")
41
- def coerce(value, round: self.class.default_round, **)
42
- return nil if value.nil?
43
-
44
- result = if value.is_a?(::BigDecimal)
45
- value
46
- elsif value.is_a?(::Float)
47
- ::Kernel.BigDecimal(value, ::Float::DIG)
48
- else
49
- parse(value)
50
- end
51
- # The class, never the value — see Types::Time#coerce.
52
- raise ArgumentError, "BigDecimal fields expect a finite number, got a non-finite #{value.class}" unless result.finite?
32
+ # @raise [ArgumentError] when the value cannot be read or is not finite
33
+ def coerce(value, round: nil, **)
34
+ coerce_with(value, round)
35
+ end
53
36
 
54
- # An explicit mode keeps the result a BigDecimal (bare round(0)
55
- # returns an Integer) and ignores the process-global
56
- # BigDecimal.mode, which a host may have set to banker's rounding.
57
- round ? result.round(round, ::BigDecimal::ROUND_HALF_UP) : result
37
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
38
+ #
39
+ # @param value [::Object]
40
+ # @param options [::Hash{::Symbol=>::Object}]
41
+ # @return [::BigDecimal, nil]
42
+ # @api private
43
+ def coerce_positional(value, options)
44
+ coerce_with(value, options[:round])
58
45
  end
59
46
 
60
- # @return [Class] the top-level +::BigDecimal+ class
47
+ # @return [::Class]
61
48
  def ruby_type
62
49
  ::BigDecimal
63
50
  end
64
51
 
65
52
  private
66
53
 
67
- # @param value [Object] a value that is neither a BigDecimal nor a Float
68
- # @return [::BigDecimal]
69
- # @raise [ArgumentError] when its string form is not a number; the
70
- # message names the class, never the value (Kernel's echoes it)
54
+ def coerce_with(value, round)
55
+ return nil if value.nil?
56
+
57
+ number = to_decimal(value)
58
+ raise ::ArgumentError, "BigDecimal fields expect a finite number, got a non-finite #{value.class}" unless number.finite?
59
+
60
+ places = round || self.class.default_round
61
+ places ? number.round(places, ::BigDecimal::ROUND_HALF_UP) : number
62
+ end
63
+
64
+ def to_decimal(value)
65
+ case value
66
+ when ::BigDecimal then value
67
+ when ::Float then value.finite? ? BigDecimal(value, 15) : value
68
+ when ::Integer, ::String then parse(value)
69
+ else unreadable(value)
70
+ end
71
+ end
72
+
71
73
  def parse(value)
72
- ::Kernel.BigDecimal(value.to_s)
73
- rescue ::ArgumentError
74
- raise ArgumentError, "BigDecimal fields could not read a #{value.class} as a number", cause: nil
74
+ BigDecimal(value.to_s, exception: false) || unreadable(value)
75
+ end
76
+
77
+ def unreadable(value)
78
+ raise ::ArgumentError, "BigDecimal fields could not read #{class_phrase(value)} as a number"
75
79
  end
76
80
  end
77
81
  end
@@ -1,37 +1,30 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'string'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # Binary type — coerces input to a String and forces +ASCII-8BIT+
8
- # encoding. Intended for raw bytes (file contents, BLOBs, etc.)
9
- # where whitespace bytes (+\x20+, +\n+, etc.) are meaningful data,
10
- # not "missing" content.
11
- #
12
- # +missing?+ is therefore +nil+-or-empty only — unlike
13
- # {Types::String} which treats whitespace-only as missing.
14
- class Binary < FieldStruct::Types::String
15
- # @param value [#to_s, nil] anything stringable; +nil+ stays +nil+
16
- # @return [::String, nil] +nil+ when input is +nil+, otherwise a
17
- # fresh ASCII-8BIT-encoded copy of +value.to_s+
5
+ # Raw bytes: a copy of the text tagged ASCII-8BIT. Whitespace is data; only nil and empty are missing.
6
+ class Binary < String
7
+ # @param value [::Object]
8
+ # @return [::String, nil] a binary copy; the input is never changed
18
9
  def coerce(value, **)
19
- result = super
20
- return nil if result.nil?
21
-
22
- result.dup.force_encoding(::Encoding::ASCII_8BIT)
10
+ text = super
11
+ text&.b
23
12
  end
24
13
 
25
- # Missing if nil or empty. Whitespace bytes are meaningful in
26
- # binary data, so they don't count as missing.
14
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
27
15
  #
28
- # @param value [Object]
29
- # @return [Boolean]
30
- def missing?(value)
31
- return true if value.nil?
32
- return true if value.respond_to?(:empty?) && value.empty?
16
+ # @param value [::Object]
17
+ # @param options [::Hash{::Symbol=>::Object}]
18
+ # @return [::String, nil]
19
+ # @api private
20
+ def coerce_positional(value, options)
21
+ super&.b
22
+ end
33
23
 
34
- false
24
+ # @param value [::Object]
25
+ # @return [Boolean] true for nil and the empty string
26
+ def missing?(value)
27
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
35
28
  end
36
29
  end
37
30
  end
@@ -1,125 +1,102 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'base'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # Boolean type. Accepts the literal +true+/+false+, the strings
8
- # "true"/"false" (case-insensitive), and the integers/strings 1/0.
9
- # Anything else raises +ArgumentError+.
10
- #
11
- # Per-field +values:+ option customizes the truthy/falsy vocabulary:
12
- #
13
- # required :active, :boolean, values: {truthy: %w[on yes y],
14
- # falsy: %w[off no n]}
15
- # required :flag, :boolean, values: :english_yes_no
16
- #
17
- # Hash form takes +:truthy+ and +:falsy+ Arrays of strings (matched
18
- # case-insensitively). Symbol form names a built-in preset; see
19
- # {.presets} for the available names.
20
- #
21
- # Ruby has no Boolean class, so {#ruby_type} returns the pair
22
- # +[TrueClass, FalseClass]+.
5
+ # True or false. Reads true/false, 1/0, and strings from a vocabulary.
23
6
  class Boolean < Base
24
- # Native options: a +values:+ Hash with +:truthy+ / +:falsy+ keys, or a
25
- # Symbol naming one of {.presets}.
26
- #
27
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
28
- def self.own_option_schema
29
- {values: option(type: [::Hash, ::Symbol], presets: presets.keys)}
30
- end
31
-
32
- # @return [Array<::String>] case-insensitive strings that coerce to true
33
- def self.default_truthy
34
- %w[true 1]
35
- end
36
-
37
- # @return [Array<::String>] case-insensitive strings that coerce to false
38
- def self.default_falsy
39
- %w[false 0]
40
- end
7
+ # Words for the +:english+ preset.
8
+ # @return [::Hash{::Symbol=>::Array<::String>}]
9
+ ENGLISH = { truthy: %w[true yes y on 1].freeze, falsy: %w[false no n off 0].freeze }.freeze
10
+ # Digits for the +:numeric+ preset.
11
+ # @return [::Hash{::Symbol=>::Array<::String>}]
12
+ NUMERIC = { truthy: ['1'].freeze, falsy: ['0'].freeze }.freeze
13
+ # Named truthy/falsy word lists.
14
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Array<::String>}}]
15
+ PRESETS = { english_yes_no: ENGLISH, english: ENGLISH, numeric: NUMERIC }.freeze
16
+
17
+ class << self
18
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}]
19
+ def own_option_schema
20
+ { values: option(type: [::Hash, ::Symbol], presets: presets.keys) }
21
+ end
41
22
 
42
- # @return [::Hash{::Symbol => ::Hash{::Symbol => ::Array<::String>}}] named presets for the +values:+ option
43
- def self.presets
44
- {
45
- english_yes_no: {truthy: %w[true yes y on 1], falsy: %w[false no n off 0]},
46
- english: {truthy: %w[true yes y on 1], falsy: %w[false no n off 0]},
47
- numeric: {truthy: %w[1], falsy: %w[0]}
48
- }
49
- end
23
+ # @return [::Array<::String>] strings read as true when a field declares no +values:+
24
+ def default_truthy
25
+ %w[true 1]
26
+ end
50
27
 
51
- # Resolve a Symbol +values:+ to its preset Hash at field-declaration
52
- # time. Pass-through for Hash form; raises for unknown preset names.
53
- def self.resolve_options(options)
54
- return options unless options.key?(:values)
55
-
56
- resolved = options.dup
57
- if resolved[:values].is_a?(::Symbol)
58
- preset = presets.fetch(resolved[:values]) do
59
- raise ArgumentError,
60
- "unknown :boolean values preset #{resolved[:values].inspect}. " \
61
- "Available: #{presets.keys.inspect}"
62
- end
63
- resolved[:values] = preset
28
+ # @return [::Array<::String>] strings read as false when a field declares no +values:+
29
+ def default_falsy
30
+ %w[false 0]
64
31
  end
65
- unless resolved[:values].is_a?(::Hash)
66
- raise ArgumentError, 'boolean values: must be a Hash {truthy:, falsy:} or a preset Symbol'
32
+
33
+ # @return [::Hash{::Symbol=>::Hash{::Symbol=>::Object}}] preset name to +{truthy:, falsy:}+
34
+ def presets
35
+ PRESETS
67
36
  end
68
37
 
69
- resolved
38
+ # Turns a +values:+ preset Symbol into its Hash.
39
+ #
40
+ # @param options [::Hash{::Symbol=>::Object}]
41
+ # @return [::Hash{::Symbol=>::Object}]
42
+ # @raise [ArgumentError] for an unknown preset
43
+ def resolve_options(options)
44
+ PresetResolver.call(options, :values, presets, label: ':boolean values')
45
+ end
70
46
  end
71
47
 
72
- # @param value [Boolean, ::Integer, ::String, nil] accepts literal
73
- # +true+/+false+; the integers +1+/+0+; or a String matched
74
- # case-insensitively against the truthy/falsy vocabularies.
75
- # Anything else raises ArgumentError.
76
- # @param values [Hash{::Symbol=>Array<::String>}, nil] +{truthy: [...], falsy: [...]}+
77
- # custom vocabulary; +nil+ uses {.default_truthy} / {.default_falsy}
48
+ # @param value [::Object]
49
+ # @param values [::Hash{::Symbol=>::Array<::String>}, nil] +{truthy: [...], falsy: [...]}+ vocabulary for String input
78
50
  # @return [Boolean, nil]
79
- # @raise [ArgumentError] when the value can't be mapped to true/false
51
+ # @raise [ArgumentError] when the value is not in the vocabulary
80
52
  def coerce(value, values: nil, **)
81
- return nil if value.nil?
82
- return value if value == true || value == false # rubocop:disable Style/MultipleComparison
83
- return true if value == 1
84
- return false if value == 0
85
-
86
- truthy, falsy = truthy_and_falsy_for(values)
87
- if value.is_a?(::String)
88
- downcased = value.downcase
89
- return true if truthy.include?(downcased)
90
- return false if falsy.include?(downcased)
91
- end
53
+ coerce_with(value, values)
54
+ end
92
55
 
93
- raise ArgumentError, refusal_message(value, truthy + falsy)
56
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
57
+ #
58
+ # @param value [::Object]
59
+ # @param options [::Hash{::Symbol=>::Object}]
60
+ # @return [Boolean, nil]
61
+ # @api private
62
+ def coerce_positional(value, options)
63
+ coerce_with(value, options[:values])
94
64
  end
95
65
 
96
- # @return [Array(Class, Class)] +[TrueClass, FalseClass]+
66
+ # @return [::Array<::Class>]
97
67
  def ruby_type
98
- [TrueClass, FalseClass]
68
+ [::TrueClass, ::FalseClass]
99
69
  end
100
70
 
101
71
  private
102
72
 
103
- # The accepted vocabulary is declared schema, so it is listed; the
104
- # refused value is named by class only — it may be payments data.
105
- #
106
- # @param value [Object] the refused input
107
- # @param accepted [Array<::String>] the truthy then falsy strings
108
- # @return [::String]
109
- def refusal_message(value, accepted)
110
- got = value.is_a?(::String) ? 'a String that is not one' : value.class.to_s
111
- "Boolean fields expect true, false, 1, 0 or one of the strings #{accepted.map(&:inspect).join(", ")}, got #{got}"
73
+ def coerce_with(value, values)
74
+ return nil if value.nil?
75
+ return true if value.equal?(true)
76
+ return false if value.equal?(false)
77
+ return value == 1 if numeric_flag?(value)
78
+
79
+ truthy, falsy = vocabulary(values)
80
+ word = value.is_a?(::String) ? value.downcase : nil
81
+ return truthy.include?(word) if (truthy + falsy).include?(word)
82
+
83
+ refuse(value, truthy + falsy)
112
84
  end
113
85
 
114
- # @param values [::Hash{::Symbol=>::Array<::String>}, nil] the field's +values:+
115
- # @return [Array(::Array<::String>, ::Array<::String>)] +[truthy, falsy]+, downcased
116
- def truthy_and_falsy_for(values)
117
- return [self.class.default_truthy, self.class.default_falsy] unless values
86
+ def numeric_flag?(value)
87
+ value.is_a?(::Numeric) && [0, 1].include?(value)
88
+ end
89
+
90
+ def vocabulary(values)
91
+ truthy = values ? values[:truthy] : self.class.default_truthy
92
+ falsy = values ? values[:falsy] : self.class.default_falsy
93
+ [truthy, falsy].map { |words| Array(words).map { |word| word.to_s.downcase } }
94
+ end
118
95
 
119
- [
120
- Array(values[:truthy]).map { |s| s.to_s.downcase },
121
- Array(values[:falsy]).map { |s| s.to_s.downcase }
122
- ]
96
+ def refuse(value, words)
97
+ got = value.is_a?(::String) ? 'a String that is not one' : value.class
98
+ listed = words.map(&:inspect).join(', ')
99
+ raise ::ArgumentError, "Boolean fields expect true, false, 1, 0 or one of the strings #{listed}, got #{got}"
123
100
  end
124
101
  end
125
102
  end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Types
5
+ # Registers every built-in type under its name.
6
+ #
7
+ # @param registry [FieldStruct::Registry]
8
+ # @return [FieldStruct::Registry] the same registry
9
+ def self.install(registry)
10
+ registry
11
+ .register(:string, String)
12
+ .register(:immutable_string, ImmutableString)
13
+ .register(:integer, Integer)
14
+ .register(:float, Float)
15
+ .register(:big_decimal, BigDecimal)
16
+ .register(:decimal, :big_decimal)
17
+ .register(:boolean, Boolean)
18
+ .register(:date, Date)
19
+ .register(:time, Time)
20
+ .register(:datetime, DateTime)
21
+ .register(:value, Value)
22
+ .register(:array, Array)
23
+ .register(:hash, Hash)
24
+ .register(:symbol, Symbol)
25
+ .register(:uuid, UUID)
26
+ .register(:url, URL)
27
+ .register(:email, Email)
28
+ .register(:union, Union)
29
+ .register(:binary, Binary)
30
+ end
31
+ end
32
+ end
@@ -1,157 +1,43 @@
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
- # Date type. Returns a +Date+ as-is, narrows a +DateTime+ or +Time+ down
9
- # to a plain Date, reads a String via +Date.parse+ (or +strptime+ when the
10
- # 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 when emitting via +as_json+ / +to_json+). When no format
15
- # is set, the type uses +Date.parse+ for input and ISO-8601 for output.
16
- class Date < Base
17
- # Native options: a +format:+ strftime/strptime String (or Symbol
18
- # preset; see {.presets}) and an +in:+ Array or Range of allowed values.
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
- }
26
- end
27
-
28
- # @return [::String, nil] field-level strftime/strptime format; +nil+
29
- # leaves the type using ISO-8601 in/out
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: the
37
- # contract cannot be written as one (see that class). The display presets
38
- # stay strftime-based — they are for humans, not wire formats.
39
- #
40
- # @return [Hash{::Symbol=>Object}]
41
- def self.presets
42
- {
43
- iso8601: Rfc3339Format.date,
44
- us: '%m/%d/%Y',
45
- eu: '%d/%m/%Y'
46
- }
47
- end
48
-
49
- # Resolve a Symbol +format:+ preset (see {.presets}) to its strftime
50
- # string at field-declaration time; other forms pass through.
51
- def self.resolve_options(options)
52
- TimeFormatResolver.call(options, presets)
53
- end
54
-
55
- # Resolve a declared +format:+ (a Symbol preset name or a strftime
56
- # String) into the String that {#coerce} and JSON rendering actually
57
- # use. Declarations are stored exactly as written, so this is where a
58
- # preset name becomes usable. See {TimeFormatResolver}.
59
- #
60
- # @param format [::String, ::Symbol, nil] the format as declared
61
- # @return [::String, nil] +nil+ when the field declares no format
62
- # @raise [ArgumentError] when a Symbol names no preset in {.presets}
63
- def self.resolve_format(format)
64
- # Skip building the presets Hash for the common, undeclared case.
65
- return format if format.nil? || format.is_a?(::String)
66
-
67
- TimeFormatResolver.resolve(format, presets)
68
- end
69
-
70
- # Dispatch is on explicit stdlib classes, never on a +respond_to?+ probe
71
- # against the value. ActiveSupport defines +String#to_date+, so a probe
72
- # that is false on plain Ruby is TRUE under Rails, and the type would take
73
- # a different branch there than it does in its own suite — which is
74
- # exactly how a declared +format:+ came to be ignored under Rails while
75
- # every spec here passed. +Date.parse+ and +Date.strptime+ are not
76
- # redefined by ActiveSupport, so dispatching on them gives one behaviour
77
- # in both worlds.
78
- #
79
- # @param value [::String, ::Date, ::DateTime, ::Time, nil] +nil+ → +nil+;
80
- # a String is read through +strptime+ when a +format:+ is set and
81
- # +Date.parse+ otherwise; a +Date+ passes through; a +DateTime+ or
82
- # +Time+ (including ActiveSupport's TimeWithZone) is narrowed to a
83
- # plain +Date+. Anything else is refused.
84
- # @param format [::String, nil] strptime/strftime format; +nil+ uses
85
- # {.default_format} (which itself defaults to +nil+ = ISO-8601 path)
86
- # @return [::Date, nil]
87
- # @raise [ArgumentError] when a String cannot be parsed, or the value is
88
- # not a String or a temporal object
89
- def coerce(value, format: self.class.default_format, **)
90
- return nil if value.nil?
91
-
92
- fmt = self.class.resolve_format(format)
93
-
94
- case value
95
- when ::String then parse_string(value, fmt)
96
- # ::DateTime is a ::Date, so this arm narrows both. A plain Date is
97
- # returned untouched; a DateTime is rebuilt as one.
98
- when ::Date then value.instance_of?(::Date) ? value : ::Date.new(value.year, value.mon, value.mday)
99
- # ActiveSupport::TimeWithZone lands here: AS overrides Time.=== so it
100
- # matches, even though it is not an instance of ::Time.
101
- when ::Time then ::Date.new(value.year, value.mon, value.mday)
102
- else
103
- # The class, never the value. FieldStruct wraps this as "could not be
104
- # coerced: <message>" and that string reaches API responses and audit
105
- # rows, so a value echoed here is a value published.
106
- raise ArgumentError, "expected a String, Date, DateTime or Time, got #{value.class}"
5
+ # A calendar date. Strings must name a whole, existing day; a declared +format:+ anchors.
6
+ class Date < Temporal
7
+ # Named formats the +format:+ option accepts (strptime Strings, or the RFC 3339 reader).
8
+ # @return [::Hash{::Symbol=>::Object}]
9
+ PRESETS = { iso8601: Rfc3339Format::DATE, us: '%m/%d/%Y', eu: '%d/%m/%Y' }.freeze
10
+
11
+ class << self
12
+ # @return [::Hash{::Symbol=>::Object}] +iso8601+ (RFC 3339), +us+ and +eu+
13
+ def presets
14
+ PRESETS
107
15
  end
108
16
  end
109
17
 
110
- # @return [Class] the top-level +::Date+ class
18
+ # @return [::Class]
111
19
  def ruby_type
112
20
  ::Date
113
21
  end
114
22
 
115
23
  private
116
24
 
117
- # @param value [::String] the raw string
118
- # @param format [::String, nil] strptime format, when the field declares one
119
- # @return [::Date]
120
- # @raise [ArgumentError] when the string cannot be read
121
- def parse_string(value, format)
122
- # Validated first, then handed to the stdlib parser: the checks decide
123
- # what is ACCEPTABLE, the stdlib still decides what the value IS, so
124
- # the two can't drift apart. See {TemporalParser} for the three rules.
125
- if format.is_a?(Rfc3339Format)
126
- parts = format.parse(value)
127
- return ::Date.new(parts[:year], parts[:mon], parts[:mday])
128
- end
129
-
130
- # The validation step has already parsed the string once; build the
131
- # Date from those parts rather than having the stdlib parse it again.
132
- if format
133
- parts = TemporalParser.strptime_parts(value, format)
134
- return date_from_parts(parts) || ::Date.strptime(value, format)
135
- end
136
-
137
- date_from_parts(TemporalParser.parse_parts(value)) || ::Date.parse(value)
25
+ # A date ignores time-of-day text.
26
+ def time_parts(_parts)
27
+ {}
138
28
  end
139
29
 
140
- # +Date.parse+ and +Date.strptime+ build the Date straight from year,
141
- # month and day whenever the parts carry all three and neither a Julian
142
- # day (+:jd+) nor a day of the year (+:yday+) — date_core.c's fast path
143
- # in +d_new_by_frags+ — so this returns the same Date. Any other shape is
144
- # left to the stdlib (+nil+).
145
- #
146
- # @param parts [::Hash{::Symbol=>Object}] already checked by {TemporalParser}
147
- # @return [::Date, nil]
148
- def date_from_parts(parts)
149
- return nil if parts.key?(:jd) || parts.key?(:yday)
30
+ def assemble(components, _zone)
31
+ ::Date.new(components[:year], components[:mon], components[:mday])
32
+ end
150
33
 
151
- year, month, day = parts.values_at(:year, :mon, :mday)
152
- return nil if year.nil? || month.nil? || day.nil?
34
+ def from_datetime(value)
35
+ ::Date.new(value.year, value.mon, value.mday)
36
+ end
37
+ alias from_time from_datetime
153
38
 
154
- ::Date.new(year, month, day)
39
+ def from_date(value, _zone)
40
+ value.instance_of?(::Date) ? value : from_datetime(value)
155
41
  end
156
42
  end
157
43
  end