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,240 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ # INTERNAL. The JSON side of {Base}: instance to JSON-ready Hash (+as_json+), and JSON text to instance (+from_json+).
5
+ module JsonCodec
6
+ FORMAT = :json
7
+
8
+ class << self
9
+ # Inside {.dump}, BigDecimals stay raw JSON numbers (FS-B106a); anywhere else they are Strings.
10
+ #
11
+ # @param record [FieldStruct::Base]
12
+ # @return [Hash{Symbol=>Object}] Symbol keys (the +:json+ mapping applies), declaration order, every field
13
+ # unless the class's +json_omit+ leaves some out
14
+ def as_json(record)
15
+ numbers = Thread.current[NUMBERS] == true
16
+ klass = record.class
17
+ metadata = klass.metadata
18
+ mapping = metadata.serialization(FORMAT)
19
+ given = klass.json_omit == :unset ? record.given_fields : nil
20
+ result = {}
21
+ metadata.each do |field|
22
+ value = record.public_send(field.name)
23
+ next if given && value.nil? && !given.include?(field.name)
24
+
25
+ result[mapping.fetch(field.name, field.name).to_sym] = convert(value, renderer_for(field), numbers?(numbers, field))
26
+ end
27
+ result
28
+ end
29
+
30
+ # +Oj.dump(record.as_json)+ with decimals as exact numbers, unless a field or its type keeps the string (FS-B106a).
31
+ # It goes through +as_json+, so a subclass's override (and +super+ inside it) is honoured. The flag is
32
+ # fiber-local, so another fiber's +as_json+ is not affected.
33
+ #
34
+ # @param record [FieldStruct::Base]
35
+ # @return [String] JSON text
36
+ def dump(record)
37
+ outer = Thread.current[NUMBERS]
38
+ Thread.current[NUMBERS] = true
39
+ Oj.dump(record.as_json, mode: :compat)
40
+ ensure
41
+ Thread.current[NUMBERS] = outer
42
+ end
43
+
44
+ # Runs the block with foreign objects written as descriptions (FS-B105a); fiber-local, restored after.
45
+ #
46
+ # @return [Object] the block's result
47
+ def describing
48
+ outer = Thread.current[DESCRIBE]
49
+ Thread.current[DESCRIBE] = true
50
+ yield
51
+ ensure
52
+ Thread.current[DESCRIBE] = outer
53
+ end
54
+
55
+ # @param klass [Class] a +FieldStruct::Base+ subclass
56
+ # @param input [String, nil] JSON text
57
+ # @return [FieldStruct::Base]
58
+ # @raise [ArgumentError] for a non-object root
59
+ # @raise [EncodingError] for malformed JSON
60
+ def load(klass, input)
61
+ parsed = parse(input)
62
+ raise ArgumentError, "from_json expects a JSON object root, got #{parsed.class}" unless parsed.is_a?(::Hash)
63
+
64
+ klass.new(canonical(klass, parsed))
65
+ end
66
+
67
+ private
68
+
69
+ # --- dumping ---
70
+
71
+ # The temporal type instance and format that render a field's values, or nil. Worked out once per Field.
72
+ def renderer_for(field)
73
+ cached = RENDERERS[field]
74
+ return cached unless cached.nil?
75
+
76
+ RENDERERS[field] = build_renderer(field) || NO_RENDERER
77
+ end
78
+
79
+ def build_renderer(field)
80
+ type = field.type_instance
81
+ return [type, field.options[:format]].freeze if type.is_a?(Types::Temporal)
82
+ return nil unless type.is_a?(Types::Array) || type.is_a?(Types::Hash)
83
+
84
+ of_type = field.options[:of_type]
85
+ element = of_type.is_a?(::Class) ? of_type.new : of_type
86
+ element.is_a?(Types::Temporal) ? [element, field.options.dig(:element, :format)].freeze : nil
87
+ end
88
+
89
+ # Inside {.dump}, whether this field's decimals go out as numbers.
90
+ def numbers?(numbers, field)
91
+ numbers && !decimal_string?(field)
92
+ end
93
+
94
+ # Whether a decimal field (or an array or map of decimals) writes Strings in +to_json+: its +json:+, else its
95
+ # type's default.
96
+ def decimal_string?(field)
97
+ type = field.type_instance
98
+ return field.options.fetch(:json) { type.class.json_default } == :string if type.is_a?(Types::BigDecimal)
99
+
100
+ (type.is_a?(Types::Array) || type.is_a?(Types::Hash)) && element_decimal_string?(field)
101
+ end
102
+
103
+ def element_decimal_string?(field)
104
+ of_type = field.options[:of_type]
105
+ klass = of_type.is_a?(::Class) ? of_type : of_type.class
106
+ return false unless klass <= Types::BigDecimal
107
+
108
+ (field.options.dig(:element, :json) || klass.json_default) == :string
109
+ end
110
+
111
+ # nil, booleans, String, Integer and Float are the values JSON carries as they are.
112
+ def convert(value, renderer, numbers)
113
+ case value
114
+ when ::NilClass, ::TrueClass, ::FalseClass, ::String, ::Integer, ::Float then value
115
+ when ::Symbol then value.to_s
116
+ when ::BigDecimal then numbers ? RawNumber.new(value) : value.to_s('F')
117
+ when ::Date, ::Time then render_temporal(value, renderer)
118
+ else convert_container(value, renderer, numbers)
119
+ end
120
+ end
121
+
122
+ def convert_container(value, renderer, numbers)
123
+ case value
124
+ when ::Array then value.map { |item| convert(item, renderer, numbers) }
125
+ when ::Hash then value.transform_values { |item| convert(item, renderer, numbers) }
126
+ else convert_object(value)
127
+ end
128
+ end
129
+
130
+ # A struct answers for itself; anything else is asked only if it can answer (the one allowlisted
131
+ # +respond_to?+ on a framework-redefinable predicate, FS-B105: this arm is only reached for :value fields).
132
+ def convert_object(value)
133
+ return value.as_json if value.is_a?(Base)
134
+ return describe(value) if Thread.current[DESCRIBE] && !value.is_a?(::Numeric)
135
+
136
+ value.respond_to?(:as_json) ? value.as_json : value
137
+ end
138
+
139
+ # "#<Lantern id=4>": reads the class and, when there is one, the id; nothing else is called.
140
+ def describe(value)
141
+ name = value.class.name || 'anonymous'
142
+ value.respond_to?(:id) ? "#<#{name} id=#{value.id}>" : "#<#{name}>"
143
+ end
144
+
145
+ def render_temporal(value, renderer)
146
+ type, format = renderer.empty? ? DEFAULT_PAIR : renderer
147
+ type.render(value, format: format)
148
+ end
149
+
150
+ # --- loading ---
151
+
152
+ def parse(input)
153
+ Oj.load(input, mode: :compat, decimal_class: ::BigDecimal)
154
+ rescue ::EncodingError, Oj::ParseError => e
155
+ raise ::EncodingError, sanitized_message(e.message), cause: nil
156
+ end
157
+
158
+ # Oj's text is "<description> (after <path>) at line L, column C [file:line] in '<input>'": keep description and position.
159
+ def sanitized_message(message)
160
+ description = message[/\A(.*?)(?: \(after |\z)/m, 1]
161
+ position = message.match(/\) at line (\d+), column (\d+) \[/)
162
+ "from_json could not parse its input as JSON (#{description}#{" at line #{position[1]}, column #{position[2]}" if position})"
163
+ end
164
+
165
+ # Rewrites a parsed object's keys to internal names, recursing where the field's type holds structs.
166
+ def canonical(klass, hash)
167
+ metadata = klass.metadata
168
+ reverse = metadata.reverse_serialization(FORMAT)
169
+ result = {}
170
+ hash.each do |key, value|
171
+ name = reverse.fetch(key.to_s) { key.to_s.to_sym }
172
+ field = metadata[name]
173
+ result[name] = field ? canonical_value(field, value) : value
174
+ end
175
+ result
176
+ end
177
+
178
+ def canonical_value(field, value)
179
+ type = field.type_instance
180
+ case type
181
+ when Types::Nested then value.is_a?(::Hash) ? canonical(type.struct_class, value) : value
182
+ when Types::Array then canonical_elements(field.options[:of_type], value)
183
+ when Types::Hash then canonical_entries(field.options[:of_type], value)
184
+ when Types::Union then value.is_a?(::Hash) ? canonical_union(type, value) : value
185
+ else value
186
+ end
187
+ end
188
+
189
+ def canonical_elements(of_type, value)
190
+ return value unless of_type.is_a?(Types::Nested) && value.is_a?(::Array)
191
+
192
+ value.map { |item| item.is_a?(::Hash) ? canonical(of_type.struct_class, item) : item }
193
+ end
194
+
195
+ def canonical_entries(of_type, value)
196
+ return value unless of_type.is_a?(Types::Nested) && value.is_a?(::Hash)
197
+
198
+ value.transform_values { |item| item.is_a?(::Hash) ? canonical(of_type.struct_class, item) : item }
199
+ end
200
+
201
+ # The first member that accepts the Hash wins: a struct member builds from the reverse-mapped Hash, any other
202
+ # member leaves the Hash as it is. When none accepts, the raw Hash goes on to the field's policy.
203
+ def canonical_union(union, hash)
204
+ union.member_types.each do |member|
205
+ return member.coerce(canonical(member.struct_class, hash)) if member.is_a?(Types::Nested)
206
+
207
+ member.coerce(hash)
208
+ return hash
209
+ rescue *Types::Union::RESCUABLE
210
+ next
211
+ end
212
+ hash
213
+ end
214
+ end
215
+
216
+ DEFAULT_PAIR = [Types::Time.new, nil].freeze
217
+ # Field => renderer pair (or NO_RENDERER); weak so dropped classes' Fields can be collected.
218
+ RENDERERS = ObjectSpace::WeakMap.new
219
+ NO_RENDERER = [].freeze
220
+ # The fiber-local key {.describing} sets (FS-B105a).
221
+ DESCRIBE = :__field_struct_describe_foreign__
222
+ # The fiber-local key {.dump} sets while +as_json+ runs.
223
+ NUMBERS = :__field_struct_json_numbers__
224
+
225
+ # A BigDecimal in the +to_json+ tree: Oj's compat mode embeds what +to_json+ returns, so the exact digits go out
226
+ # as a JSON number (FS-B106a; measured with Oj 3.17.8, with and without the json library loaded).
227
+ class RawNumber
228
+ # @param decimal [BigDecimal]
229
+ def initialize(decimal)
230
+ @text = decimal.to_s('F')
231
+ end
232
+
233
+ # @return [String] the plain digits
234
+ def to_json(*)
235
+ @text
236
+ end
237
+ end
238
+ private_constant :DEFAULT_PAIR, :RENDERERS, :NO_RENDERER, :DESCRIBE, :NUMBERS, :RawNumber
239
+ end
240
+ end
@@ -1,30 +1,34 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FieldStruct
4
- # The per-class collection of {Field} declarations.
5
- #
6
- # Mutable while a class is being defined — the DSL adds fields as it
7
- # encounters them — and queried thereafter by name or via iteration.
8
- # Subclass inheritance is handled by {#merge}: a fresh child Metadata
9
- # is seeded with the parent's fields, then accumulates its own; child
10
- # declarations win on conflict.
4
+ # Ordered collection of a class's Fields, plus its per-format serialization mappings.
11
5
  class Metadata
12
6
  include Enumerable
13
7
 
8
+ # One shared, frozen mapping for formats that were never declared.
9
+ # @return [::Hash{::Symbol=>::String}]
10
+ NO_MAPPING = {}.freeze
11
+ NO_REVERSE = {}.freeze
12
+ private_constant :NO_REVERSE
13
+
14
14
  def initialize
15
15
  @fields = {}
16
16
  @serializations = {}
17
- @reverse_serializations = {}
17
+ @reverse = {}
18
18
  end
19
19
 
20
- # @return [Hash{Symbol=>Hash{Symbol=>String}}] declared
21
- # external-name mappings keyed by format name. Each inner hash
22
- # maps an internal field name (Symbol) to its external name
23
- # (String). Fields not listed in an inner hash serialize under
24
- # their canonical name.
25
- attr_reader :serializations
20
+ # @yieldparam field [FieldStruct::Field]
21
+ # @return [Enumerator<FieldStruct::Field>, self]
22
+ def each(&block)
23
+ return enum_for(:each) unless block
26
24
 
27
- # @param field [Field]
25
+ @fields.each_value(&block)
26
+ self
27
+ end
28
+
29
+ # Adds a field; a field with the same name is replaced in place.
30
+ #
31
+ # @param field [FieldStruct::Field]
28
32
  # @return [self]
29
33
  def add(field)
30
34
  @fields[field.name] = field
@@ -32,300 +36,101 @@ module FieldStruct
32
36
  end
33
37
 
34
38
  # @param name [Symbol, String]
35
- # @return [Field, nil]
39
+ # @return [FieldStruct::Field, nil]
36
40
  def [](name)
37
41
  @fields[name.to_sym]
38
42
  end
39
43
 
40
- # @return [Array<Symbol>] field names in insertion order
44
+ # @return [Array<Symbol>] a new Array each call
41
45
  def names
42
46
  @fields.keys
43
47
  end
44
48
 
45
- # Yields each {Field} in insertion order.
46
- #
47
- # @yield [field]
48
- # @yieldparam field [Field]
49
- # @return [Enumerator<Field>] when no block is given
50
- def each(&block)
51
- @fields.each_value(&block)
52
- end
53
-
54
- # A copy-pasteable schema view of the declared fields, keyed by field
55
- # name. Each value is a plain Hash of primitives/strings (no live type
56
- # objects), so the result reads cleanly in a console and is safe to
57
- # `pp` or dump — handy for seeing a model's shape without reading its
58
- # source. Option values that are classes or type instances are rendered
59
- # as short names; a callable default shows as +"<callable>"+.
60
- #
61
- # User.metadata.to_h
62
- # # => { name: { type: "String", ruby_type: "String", required: true,
63
- # # default: nil, options: {}, description: nil }, ... }
64
- #
65
- # When a block is given this falls back to +Enumerable#to_h+ (mapping
66
- # each {Field} to a pair), preserving existing callers.
67
- #
68
- # @return [Hash{Symbol=>Hash{Symbol=>Object, nil}}] field name → schema, or
69
- # the block-mapped pairs when a block is supplied
70
- def to_h(&block)
71
- return super if block
72
-
73
- @fields.transform_values { |field| field_schema(field) }
74
- end
49
+ # @return [Hash{Symbol=>Hash{Symbol=>String}}] format name to its mapping
50
+ attr_reader :serializations
75
51
 
76
- # Record a serialization mapping for the named format. Repeats on
77
- # the same format name replace the prior mapping (last-write-wins).
78
- # The mapping is frozen on its way in.
52
+ # Stores a mapping (frozen) for a format.
79
53
  #
80
- # @param name [Symbol, String]
81
- # @param mapping [Hash{Symbol=>String}]
54
+ # @param name [Symbol, String] the format
55
+ # @param mapping [Hash{Symbol=>String}] internal field name to external name
82
56
  # @return [self]
57
+ # @api private
83
58
  def add_serialization(name, mapping)
84
- @serializations[name.to_sym] = mapping.freeze
59
+ @serializations[name.to_sym] = mapping.frozen? ? mapping : mapping.dup.freeze
85
60
  self
86
61
  end
87
62
 
88
- # Look up the mapping for a format. Returns an empty hash when the
89
- # format hasn't been declared — the implicit identity mapping that
90
- # serializers fall back to.
91
- #
92
63
  # @param name [Symbol, String]
93
- # @return [Hash{Symbol=>String}] frozen mapping (empty hash when undeclared)
64
+ # @return [Hash{Symbol=>String}] the frozen mapping, or a shared empty frozen Hash
94
65
  def serialization(name)
95
- @serializations[name.to_sym] || EMPTY_SERIALIZATION
66
+ @serializations.fetch(name.to_sym, NO_MAPPING)
96
67
  end
97
68
 
98
- # The reverse of {#serialization}: external name → field name, which
99
- # {Base.from_json} needs on every call. Built once per mapping and reused
100
- # while {#serialization} still returns that same frozen mapping, so any
101
- # writer that installs a new one ({#add_serialization}, {#merge}, or a
102
- # direct write to {#serializations}) is picked up on the next call.
103
- #
104
- # @api private
105
69
  # @param name [Symbol, String]
106
- # @return [Hash{String=>Symbol}] frozen; empty when the format is undeclared
70
+ # @return [Hash{String=>Symbol}] external name to internal name; empty if undeclared
107
71
  def reverse_serialization(name)
72
+ mapping = serialization(name)
73
+ return NO_REVERSE if mapping.empty?
74
+
108
75
  key = name.to_sym
109
- mapping = serialization(key)
110
- cached = @reverse_serializations[key]
76
+ cached = @reverse[key]
111
77
  return cached.last if cached && cached.first.equal?(mapping)
112
78
 
113
- reverse = mapping.each_with_object({}) { |(internal, external), out| out[external] = internal }.freeze
114
- # A mapping that isn't frozen could change in place, so it isn't cached.
115
- @reverse_serializations[key] = [mapping, reverse] if mapping.frozen?
79
+ reverse = mapping.to_h { |internal, external| [external, internal] }.freeze
80
+ @reverse[key] = [mapping, reverse] if mapping.frozen?
116
81
  reverse
117
82
  end
118
83
 
119
- # The identity mapping {#serialization} returns for an undeclared format.
120
- # @return [Hash{Symbol=>String}]
121
- EMPTY_SERIALIZATION = {}.freeze
122
- private_constant :EMPTY_SERIALIZATION
123
-
124
- # Copy fields and serializations from +parent+ into self, leaving
125
- # already-declared entries untouched (child wins). Order: existing
126
- # self fields stay where they are; parent fields are appended in
127
- # iteration order if not present.
84
+ # Adds every field and mapping of +parent+ that the receiver lacks. The receiver wins.
128
85
  #
129
- # @param parent [Metadata]
86
+ # @param parent [FieldStruct::Metadata]
130
87
  # @return [self]
88
+ # @api private
131
89
  def merge(parent)
132
- parent.each do |field|
133
- @fields[field.name] = field unless @fields.key?(field.name)
134
- end
135
- parent.serializations.each do |name, mapping|
136
- @serializations[name] = mapping unless @serializations.key?(name)
137
- end
90
+ parent.each { |field| @fields[field.name] = field unless @fields.key?(field.name) }
91
+ parent.serializations.each { |format, mapping| @serializations[format] = mapping unless @serializations.key?(format) }
138
92
  self
139
93
  end
140
94
 
141
- # Concise one-line representation. Lists the declared field names
142
- # and, when present, the declared serialization formats — without
143
- # dumping the underlying ivar hashes.
95
+ # Without a block, the schema view (FS-B121): +{name => {type:, ruby_type:, required:, default:, options:, description:}}+
96
+ # (plus +rbs_type+ and +sensitive+ when set), values made primitive. With a block it is +Enumerable#to_h+.
144
97
  #
145
- # @return [String]
146
- def inspect
147
- return "#<#{FieldStruct.inspect_namespace}::Metadata empty>" if @fields.empty?
148
-
149
- parts = ["fields=#{@fields.keys.inspect}"]
150
- parts << "serializations=#{@serializations.keys.inspect}" unless @serializations.empty?
151
- "#<#{FieldStruct.inspect_namespace}::Metadata #{parts.join(" ")}>"
152
- end
153
-
154
- # Multi-line representation suitable for IRB / pp. Renders each
155
- # field on its own indented line using {Field#inspect}, with the
156
- # closing +>+ on its own line.
157
- #
158
- # @param pp [Object] a PP-shaped sink (responds to +#text+)
159
- # @return [void]
160
- def pretty_print(pp)
161
- if @fields.empty?
162
- pp.text(inspect)
163
- return
164
- end
98
+ # @return [Hash{Symbol=>Hash{Symbol=>Object, nil}}]
99
+ def to_h(&block)
100
+ return super if block
165
101
 
166
- pp.text("#<#{FieldStruct.inspect_namespace}::Metadata")
167
- @fields.each_value do |field|
168
- pp.text("\n ")
169
- pp.text(field.inspect)
170
- end
171
- pp.text("\n serializations=#{@serializations.keys.inspect}") unless @serializations.empty?
172
- pp.text("\n>")
102
+ to_h { |field| [field.name, Describer.schema(field)] }
173
103
  end
174
104
 
175
- # Human/agent-readable summary of the declared fields: one line each
176
- # with the field's type, required-ness, and the native options its type
177
- # accepts (with value shapes, required options starred, and any presets).
178
- # Answers "what can I put here?" without reading source. For the
179
- # structured form use {#to_h}; for a class-titled version use
180
- # {Base.describe}.
181
- #
182
- # name (String, required) — accepts format (Regexp | Symbol), enum (Array)
105
+ # One line per field: the field's name, a parenthesised label, and what it accepts (FS-B122).
183
106
  #
184
- # @return [String]
107
+ # @return [String] +(no fields)+ when empty
185
108
  def describe
186
109
  return '(no fields)' if @fields.empty?
187
110
 
188
- @fields.each_value.map { |field| describe_field(field) }.join("\n")
189
- end
190
-
191
- private
192
-
193
- # @param field [Field]
194
- # @return [String] one +describe+ line for a field
195
- def describe_field(field)
196
- flags = [short_name(field.type), field.required? ? 'required' : 'optional']
197
- flags << 'sensitive' if field.sensitive?
198
- label = " #{field.name} (#{flags.join(", ")})"
199
- parts = [label, declared_options_summary(field), accepts_summary(field.type), element_accepts_summary(field)].compact
200
-
201
- parts.join(' — ')
202
- end
203
-
204
- # What this field actually declares, as written.
205
- #
206
- # Without this, +describe+ answered only "what COULD go in this field" —
207
- # the type's option vocabulary — and a field declaring
208
- # +format: :iso8601, enum: %w[USD EUR]+ rendered identically to one
209
- # declaring nothing at all. The option schema belongs to the type; this
210
- # belongs to the field.
211
- #
212
- # @param field [Field]
213
- # @return [String, nil] +nil+ when the field declares no options
214
- def declared_options_summary(field)
215
- # Every temporal field carries `format: nil` from apply_default_format,
216
- # so nils are dropped rather than rendered as a declaration that isn't one.
217
- declared = field.options.compact
218
- return nil if declared.empty?
219
-
220
- declared.map { |key, value| "#{key}: #{declared_option_repr(value)}" }.join(', ')
221
- end
222
-
223
- # @return [String] a declared option value, rendered for a human. Type
224
- # values (an Array field's +of_type:+) show their bare type name rather
225
- # than a quoted string, so the line reads like the declaration it
226
- # describes.
227
- # @param value [Object, nil] a declared option value
228
- def declared_option_repr(value)
229
- case value
230
- when FieldStruct::Types::Nested then "Nested(#{short_name(value.struct_class)})"
231
- when FieldStruct::Types::Base then short_name(value.class)
232
- when ::Class then short_name(value)
233
- # Spelled out rather than Hash#inspect, whose format changed in Ruby 3.4.
234
- when ::Hash then "{#{value.map { |key, item| "#{key}: #{declared_option_repr(item)}" }.join(", ")}}"
235
- else value.inspect
236
- end
111
+ map { |field| Describer.describe_field(field) }.join("\n")
237
112
  end
238
113
 
239
- # What an array field's +element:+ may hold — the names of its element
240
- # type's native options — so the line answers "what can I pass to each
241
- # element" too.
114
+ # Fans out one field per line (FS-B120).
242
115
  #
243
- # @param field [Field]
244
- # @return [String, nil] +nil+ for a non-array field, or an element type
245
- # with no options (a nested struct)
246
- def element_accepts_summary(field)
247
- return nil unless field.type <= FieldStruct::Types::Array
248
-
249
- # Names only: the shapes are the element type's own (its
250
- # +option_schema+), and repeating them doubled every array line.
251
- element_class = FieldStruct::Types::Array.element_class(field.options[:of_type])
252
- return nil unless element_class.respond_to?(:option_schema)
253
-
254
- names = element_class.option_schema.keys
255
- names.empty? ? nil : "element accepts #{names.join(", ")}"
256
- end
257
-
258
- # @return [String, nil] the type's native option vocabulary, or +nil+ when
259
- # the type declares none
260
- # @param type_class [Class<Types::Base>]
261
- def accepts_summary(type_class)
262
- accepts = native_options_summary(type_class)
263
- accepts.empty? ? nil : "accepts #{accepts}"
264
- end
265
-
266
- # @return [String] the type's native options as +name(shapes)+, required
267
- # ones starred, presets appended — empty when the type has none
268
- # @param type_class [Class<Types::Base>]
269
- def native_options_summary(type_class)
270
- return '' unless type_class.respond_to?(:option_schema)
271
-
272
- type_class.option_schema.map do |name, descriptor|
273
- shapes = descriptor[:type].map { |klass| short_name(klass) }.join(' | ')
274
- star = descriptor[:required] ? '*' : ''
275
- presets = descriptor[:presets].empty? ? '' : "; presets: #{descriptor[:presets].join(", ")}"
276
- "#{name}#{star} (#{shapes}#{presets})"
277
- end.join(', ')
278
- end
116
+ # @param printer [PP]
117
+ # @return [void]
118
+ def pretty_print(printer)
119
+ return printer.text(inspect) if @fields.empty? && @serializations.empty?
279
120
 
280
- # Render one field as a primitive-only schema Hash for {#to_h}.
281
- #
282
- # @param field [Field]
283
- # @return [Hash{Symbol=>Object, nil}]
284
- def field_schema(field)
285
- schema = {
286
- type: short_name(field.type),
287
- ruby_type: ruby_type_repr(field.type_instance.ruby_type),
288
- required: field.required?,
289
- default: schema_value(field.default),
290
- options: field.options.transform_values { |value| schema_value(value) },
291
- description: field.description
292
- }
293
- # Only when set, so the schema of a field without one is unchanged.
294
- schema[:rbs_type] = field.rbs_type if field.rbs_type
295
- schema[:sensitive] = true if field.sensitive?
296
- schema
121
+ text = "#<#{FieldStruct.inspect_namespace}::Metadata"
122
+ each { |field| text << "\n #{field.inspect}" }
123
+ text << "\n serializations=#{@serializations.keys.inspect}" unless @serializations.empty?
124
+ printer.text("#{text}\n>")
297
125
  end
298
126
 
299
- # A single class, or +A | B+ for a multi-class ruby_type (boolean, union).
300
- #
301
- # @param ruby_type [Class, Array<Class>] a type's {Types::Base#ruby_type}
302
127
  # @return [String]
303
- def ruby_type_repr(ruby_type)
304
- Array(ruby_type).map(&:name).join(' | ')
305
- end
306
-
307
- # Reduce an option/default value to something printable: short class
308
- # names for type references, +"<callable>"+ for procs, recursion into
309
- # Array/Hash, everything else as-is.
310
- #
311
- # @param value [Object, nil] an option or default value
312
- # @return [Object, nil]
313
- def schema_value(value)
314
- case value
315
- when nil, true, false, ::Numeric, ::String, ::Symbol, ::Regexp, ::Range then value
316
- when ::Class then short_name(value)
317
- when FieldStruct::Types::Base then short_name(value.class)
318
- when ::Array then value.map { |element| schema_value(element) }
319
- when ::Hash then value.transform_values { |element| schema_value(element) }
320
- else
321
- value.respond_to?(:call) ? '<callable>' : value
322
- end
323
- end
128
+ def inspect
129
+ prefix = "#<#{FieldStruct.inspect_namespace}::Metadata"
130
+ return "#{prefix} empty>" if @fields.empty? && @serializations.empty?
324
131
 
325
- # @param klass [Module]
326
- # @return [String] the last segment of the class name
327
- def short_name(klass)
328
- klass.name.to_s.split('::').last
132
+ suffix = @serializations.empty? ? '' : " serializations=#{@serializations.keys.inspect}"
133
+ "#{prefix} fields=#{names.inspect}#{suffix}>"
329
134
  end
330
135
  end
331
136
  end