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,179 +1,113 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FieldStruct
4
- # A single declared attribute on a FieldStruct class.
5
- #
6
- # Holds the field's name, the resolved type class, whether it's
7
- # required, an optional default, and any remaining keyword options
8
- # (e.g. +format:+). Frozen after construction — the DSL is expected
9
- # to build a fresh Field rather than mutate one.
4
+ # One declared attribute. Immutable once built.
10
5
  class Field
11
- # @return [Symbol] canonical field name
6
+ # @return [Symbol]
12
7
  attr_reader :name
13
-
14
- # @return [Class<Types::Base>] the resolved type class
8
+ # @return [Class] the type class (+Types::BigDecimal+ for +:decimal+)
15
9
  attr_reader :type
16
-
17
- # @return [Object, #call, nil] the configured default value, or a
18
- # parameterless callable returning one, or +nil+ if no default
19
- attr_reader :default
20
-
21
- # @return [Hash{Symbol=>Object, nil}] frozen, holds the remaining keyword
22
- # options forwarded to {Types::Base#coerce} (e.g. +:format+,
23
- # +:round+, +:values+, +:of_type+, +:enum+, +:in+)
24
- attr_reader :options
25
-
26
- # @return [Types::Base] an eagerly-built instance of {#type}, reused by
27
- # the setter pipeline so we don't allocate a fresh type per coercion
10
+ # @return [FieldStruct::Types::Base] the instance the setter pipeline uses
28
11
  attr_reader :type_instance
29
-
30
- # @return [:keep_raw, :replace, :raise, nil] this field's coercion-
31
- # failure policy override, or +nil+ to defer to the class-level
32
- # setting on {Base.coercion_policy}.
12
+ # @return [Object] the raw default: a literal, a callable, or nil for none
13
+ attr_reader :default
14
+ # @return [Symbol, nil] per-field coercion policy override
33
15
  attr_reader :coercion_policy
34
-
35
- # @return [String, nil] human-readable description of the field;
36
- # intended for downstream documentation generators. Not part of
37
- # the data surface — does not appear in +attributes+ / +as_json+ /
38
- # pattern matches.
16
+ # @return [String, nil]
39
17
  attr_reader :description
40
-
41
- # @return [String, nil] an RBS type expression that {RBS.generate} and
42
- # {RBS.type_for} emit for this field instead of deriving one from the
43
- # type (e.g. +"::ActiveRecord::Relation"+ on a +:value+ field), or
44
- # +nil+ to derive it. Declared with the +rbs_type:+ field option;
45
- # signatures only — it never affects coercion or validation.
18
+ # @return [String, nil] an RBS type that replaces the derived one
46
19
  attr_reader :rbs_type
20
+ # @return [Hash{Symbol=>Object, nil}] frozen native and pass-through options
21
+ attr_reader :options
47
22
 
48
- # @api private
49
- # @return [Symbol] the setter's method name (+:name=+), built once here
50
- # so the setter pipeline doesn't intern a dynamic Symbol per call
51
- attr_reader :setter_name
52
-
53
- # @api private
54
- # @return [Symbol] the instance variable holding the value (+:@name+),
55
- # built once for the same reason as {#setter_name}
56
- attr_reader :ivar_name
57
-
58
- # @param name [Symbol, String] canonical field name
59
- # @param type [Class<Types::Base>] the resolved type class
60
- # @param type_instance [Types::Base, nil] optional pre-built instance —
61
- # used by the DSL for parameterized types (e.g. {Types::Nested}) where
62
- # +type.new+ wouldn't be enough to capture the parameterization. When
63
- # nil, +type.new+ is called.
23
+ # @param name [Symbol, String]
24
+ # @param type [Class] a +Types::Base+ subclass
25
+ # @param type_instance [FieldStruct::Types::Base, nil] defaults to +type.new+
64
26
  # @param required [Boolean]
65
- # @param default [Object, nil] literal default value, or a
66
- # parameterless callable (Proc/Lambda/Method) that returns one.
67
- # Callables are invoked once per instance during apply_defaults.
68
- # @param coercion_policy [:keep_raw, :replace, :raise, nil] override
69
- # the class-level coercion policy for this one field; +nil+ means
70
- # "use whatever the class says"
71
- # @param description [String, nil] human-readable description of the
72
- # field; for documentation purposes only
73
- # @param rbs_type [String, nil] RBS type expression overriding the
74
- # derived one in generated signatures (see {#rbs_type})
75
- # @param sensitive [Boolean] mask the value in {Base#inspect} (see {#sensitive?})
76
- # @param options [Object, nil] extra keyword type/field options
77
- # forwarded to coerce (e.g. +format:+, +of_type:+, +round:+,
78
- # +values:+, +enum:+, +in:+)
79
- def initialize(name:, type:, type_instance: nil, required: false, default: nil, coercion_policy: nil, description: nil, rbs_type: nil, sensitive: false, **options)
27
+ # @param nullable [Boolean] a required field whose key must be given but may hold nil (FS-B34)
28
+ # @param default [Object] a literal or a callable
29
+ # @param coercion_policy [Symbol, nil]
30
+ # @param description [String, nil]
31
+ # @param rbs_type [String, nil]
32
+ # @param sensitive [Boolean]
33
+ # @param options [Object] native and pass-through options (keyword arguments)
34
+ def initialize(name:, type:, type_instance: nil, required: false, default: nil, coercion_policy: nil,
35
+ description: nil, rbs_type: nil, sensitive: false, nullable: false, **options)
80
36
  @name = name.to_sym
81
37
  @setter_name = :"#{@name}="
82
38
  @ivar_name = :"@#{@name}"
83
39
  @type = type
84
- @required = required
85
- @default = default
86
- @options = options.freeze
87
40
  @type_instance = type_instance || type.new
41
+ @required = required ? true : false
42
+ @nullable = nullable ? true : false
43
+ @default = default
88
44
  @coercion_policy = coercion_policy
89
45
  @description = description
90
46
  @rbs_type = rbs_type
91
- @sensitive = sensitive
47
+ @sensitive = sensitive ? true : false
48
+ @options = options.freeze
49
+ @positional = @type_instance.class.positional_coerce?
92
50
  freeze
93
51
  end
94
52
 
53
+ # Internal: the setter's coerce call. Built-ins take the options as one Hash, with no keyword splat
54
+ # (Types::Base.positional_coerce?); any other type gets them as keywords, and none when there are none.
55
+ #
56
+ # @param value [::Object]
57
+ # @return [::Object]
58
+ # @api private
59
+ def coerce_value(value)
60
+ if @positional then @type_instance.coerce_positional(value, @options)
61
+ elsif @options.empty? then @type_instance.coerce(value)
62
+ else @type_instance.coerce(value, **@options)
63
+ end
64
+ end
65
+
66
+ # Same as {#description}.
67
+ #
68
+ # @return [String, nil]
69
+ def desc
70
+ @description
71
+ end
72
+
95
73
  # @return [Boolean]
96
74
  def required?
97
75
  @required
98
76
  end
99
77
 
100
- # Whether the field holds data that must not reach a log — a card
101
- # number, a CVV, a token. {Base#inspect} (and so +pp+) renders
102
- # {FieldStruct::FILTERED} in place of a non-nil value. Data paths —
103
- # the reader, +attributes+, +to_h+, +as_json+, +to_json+, pattern
104
- # matching — return the real value, so round-trips stay exact.
105
- # Declared with the +sensitive:+ field option.
106
- #
107
- # @return [Boolean]
78
+ # @return [Boolean] whether the field is required but a given +nil+ satisfies it (FS-B34)
79
+ def nullable?
80
+ @nullable
81
+ end
82
+
83
+ # @return [Boolean] whether +inspect+ masks this field's value
108
84
  def sensitive?
109
85
  @sensitive
110
86
  end
111
87
 
112
- # @return [String, nil] shorter alias of {#description}
113
- alias desc description
114
-
115
- # Concise one-line representation. Designed to be readable in IRB
116
- # without dumping every ivar (the default Object#inspect is the
117
- # reason +optional :x, :string+ in a console looks like a wall of
118
- # text).
119
- #
120
- # @return [String]
88
+ # @return [String] +#<FieldStruct::Field :name Type flag... part...>+ (FS-B119)
121
89
  def inspect
122
- parts = [@name.inspect, type_repr]
123
- parts << 'required' if @required
124
- parts << 'sensitive' if @sensitive
125
- parts << "default=#{@default.inspect}" unless @default.nil?
126
- parts << "coercion_policy=#{@coercion_policy.inspect}" if @coercion_policy
127
- parts << "description=#{@description.inspect}" if @description
128
- parts << "rbs_type=#{@rbs_type.inspect}" if @rbs_type
129
- @options.each { |key, value| parts << "#{key}=#{option_repr(value)}" }
130
- "#<#{FieldStruct.inspect_namespace}::Field #{parts.join(" ")}>"
90
+ Describer.inspect_field(self)
131
91
  end
132
92
 
133
- # Delegates pretty-print to {#inspect} so IRB / pp don't fall back
134
- # to the default reflection-based output.
93
+ # Prints {#inspect} on one line.
135
94
  #
136
- # @param pp [Object] a PP-shaped sink (responds to +#text+)
95
+ # @param printer [PP]
137
96
  # @return [void]
138
- def pretty_print(pp)
139
- pp.text(inspect)
97
+ def pretty_print(printer)
98
+ printer.text(inspect)
140
99
  end
141
100
 
142
- private
143
-
144
- # @return [String] the type's short name, or +Nested(...)+ / +Union(...)+
145
- def type_repr
146
- base = @type.name.to_s.split('::').last
147
- if @type <= FieldStruct::Types::Nested
148
- "Nested(#{@type_instance.struct_class.name || "AnonymousFieldStruct"})"
149
- elsif @type <= FieldStruct::Types::Union
150
- members = @type_instance.member_types.map { |m| m.class.name.to_s.split('::').last }
151
- "Union(#{members.join(" | ")})"
152
- else
153
- base
154
- end
101
+ # @return [Symbol] the writer method name
102
+ # @api private
103
+ def setter_name # rubocop:disable Style/TrivialAccessors
104
+ @setter_name
155
105
  end
156
106
 
157
- # Render an option's value in inspect output. Type-class values
158
- # (e.g. +:of_type+ on an Array field) get their basename instead
159
- # of the full +FieldStruct::Types::String+ class.inspect.
160
- #
161
- # @param value [Object, nil] an option value
162
- # @return [String]
163
- def option_repr(value)
164
- case value
165
- when ::Class
166
- value.name.to_s.split('::').last
167
- when FieldStruct::Types::Nested
168
- "Nested(#{value.struct_class.name || "AnonymousFieldStruct"})"
169
- when FieldStruct::Types::Base
170
- value.class.name.to_s.split('::').last
171
- # Spelled out rather than Hash#inspect, whose format changed in Ruby 3.4.
172
- when ::Hash
173
- "{#{value.map { |key, item| "#{key}: #{option_repr(item)}" }.join(", ")}}"
174
- else
175
- value.inspect
176
- end
107
+ # @return [Symbol] the instance variable holding the value
108
+ # @api private
109
+ def ivar_name # rubocop:disable Style/TrivialAccessors
110
+ @ivar_name
177
111
  end
178
112
  end
179
113
  end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ # Turns the arguments of +field+ / +required+ / +optional+ into a {Field}.
5
+ module FieldBuilder
6
+ # Options valid on any field; they become Field attributes and are not passed to +coerce+.
7
+ UNIVERSAL_OPTIONS = %i[required nullable default coercion_policy description desc rbs_type sensitive].freeze
8
+
9
+ # @param owner [Class] the +Base+ subclass doing the declaring
10
+ # @param name [Symbol, String]
11
+ # @param type [Symbol, String, Class]
12
+ # @param options [Hash{Symbol=>Object}]
13
+ # @return [FieldStruct::Field]
14
+ # @raise [ArgumentError, KeyError] for a misdeclared field
15
+ def self.call(owner, name, type, options)
16
+ name = name.to_sym
17
+ reject_reserved(name)
18
+ universal = options.slice(*UNIVERSAL_OPTIONS)
19
+ check_universal(universal)
20
+ registry = owner.namespace_registry
21
+ type_class, nested = resolve_type(owner, type)
22
+ label = label(owner, name)
23
+ resolved = OptionChecker.call(type_class, options.except(*UNIVERSAL_OPTIONS), registry: registry, field_name: name, label: label)
24
+ instance, stored = nested ? [nested, resolved] : type_class.instantiate(resolved)
25
+ Field.new(name: name, type: type_class, type_instance: instance, required: universal[:required], default: universal[:default],
26
+ coercion_policy: universal[:coercion_policy], description: description_from(universal),
27
+ rbs_type: universal[:rbs_type], sensitive: universal[:sensitive], nullable: universal[:nullable], **stored)
28
+ end
29
+
30
+ # How messages name a field: +Class#field+, or +field :name+ for an anonymous class.
31
+ #
32
+ # @param owner [Class]
33
+ # @param name [Symbol]
34
+ # @return [String]
35
+ def self.label(owner, name)
36
+ owner.name ? "#{owner.name}##{name}" : "field #{name.inspect}"
37
+ end
38
+
39
+ def self.reject_reserved(name)
40
+ return unless Base::RESERVED_FIELD_NAMES.include?(name)
41
+
42
+ raise ArgumentError,
43
+ "field #{name.inspect} is reserved: FieldStruct::Base relies on ##{name}, and a field would shadow it. " \
44
+ "Pick another name; serialize :json can keep the external key (e.g. serialize :json, #{name}_field: '#{name}')."
45
+ end
46
+
47
+ # Step 2 of the declaration order: description/desc, coercion_policy, rbs_type, sensitive, nullable.
48
+ def self.check_universal(universal)
49
+ description_from(universal)
50
+ check_policy(universal[:coercion_policy])
51
+ check_rbs_type(universal[:rbs_type]) if universal.key?(:rbs_type)
52
+ check_sensitive(universal[:sensitive]) if universal.key?(:sensitive)
53
+ check_nullable(universal) if universal.key?(:nullable)
54
+ end
55
+
56
+ def self.check_nullable(universal)
57
+ value = universal[:nullable]
58
+ raise ArgumentError, "nullable: must be true or false, got #{value.class}" unless [true, false].include?(value)
59
+ return unless value && !universal[:required]
60
+
61
+ raise ArgumentError, 'nullable: applies to required fields; an optional field already accepts nil'
62
+ end
63
+
64
+ def self.check_policy(policy)
65
+ return if policy.nil? || Base::VALID_COERCION_POLICIES.include?(policy)
66
+
67
+ raise ArgumentError, "unknown coercion policy #{policy.inspect} (expected one of #{Base::VALID_COERCION_POLICIES.inspect})"
68
+ end
69
+
70
+ def self.check_rbs_type(value)
71
+ return if value.nil? || (value.is_a?(::String) && !value.strip.empty?)
72
+
73
+ raise ArgumentError, "rbs_type: must be a non-empty String of RBS (e.g. rbs_type: '::ActiveRecord::Relation'), got #{value.inspect}"
74
+ end
75
+
76
+ def self.check_sensitive(value)
77
+ return if [true, false].include?(value)
78
+
79
+ raise ArgumentError, "sensitive: must be true or false, got #{value.class}"
80
+ end
81
+
82
+ def self.description_from(universal)
83
+ raise ArgumentError, 'pass either description: or desc:, not both' if universal.key?(:description) && universal.key?(:desc)
84
+
85
+ universal[:description] || universal[:desc]
86
+ end
87
+
88
+ # @return [Array(Class, FieldStruct::Types::Nested)] the type class and, for a nested struct, its instance
89
+ def self.resolve_type(owner, type)
90
+ klass = type.is_a?(::Class) ? type : owner.resolve_type(type)
91
+ return [Types::Nested, Types::Nested.new(klass)] if nested?(klass)
92
+ raise ArgumentError, not_a_type_message(owner, klass) unless klass.is_a?(::Class) && klass <= Types::Base
93
+
94
+ [klass, nil]
95
+ end
96
+
97
+ def self.not_a_type_message(owner, klass)
98
+ message = "#{klass.inspect} is not a FieldStruct type (subclass FieldStruct::Types::Base)"
99
+ lookalike = klass.is_a?(::Module) ? owner.namespace_registry.name_for_lookalike(klass) : nil
100
+ lookalike ? "#{message}; did you mean #{lookalike.inspect}?" : message
101
+ end
102
+
103
+ def self.nested?(klass)
104
+ klass.is_a?(::Class) && klass < Base
105
+ end
106
+
107
+ private_class_method :reject_reserved, :check_universal, :check_policy, :check_rbs_type, :check_sensitive, :check_nullable,
108
+ :description_from, :resolve_type, :not_a_type_message, :nested?
109
+ end
110
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ # The per-field checks the setter runs after coercing (section 5.3): missing values, restrictions, invalid nested
5
+ # structs and +element:+ restrictions on array elements and map values. Included into {Base}.
6
+ module FieldChecks
7
+ private
8
+
9
+ def fs_validate(field, value)
10
+ errors.clear(field.name)
11
+ if field.type_instance.missing?(value)
12
+ errors.add(field.name, 'is required') if field.required? && !fs_null_answer?(field, value)
13
+ elsif (problem = Restrictions.problem(value, field.options) || ('is invalid' if fs_invalid_struct?(field, value)))
14
+ errors.add(field.name, problem)
15
+ else
16
+ fs_validate_elements(field, value)
17
+ end
18
+ end
19
+
20
+ # A nested struct, or an Array or a +:hash+ field's Hash holding at least one, that is itself invalid.
21
+ def fs_invalid_struct?(field, value)
22
+ return value.invalid? if value.is_a?(Base)
23
+
24
+ items = value.is_a?(::Array) ? value : fs_map_values(field, value)
25
+ items ? items.any? { |item| item.is_a?(Base) && item.invalid? } : false
26
+ end
27
+
28
+ # The values of a +:hash+ field's Hash, or nil for anything else (a Hash elsewhere is not walked, FS-B39).
29
+ def fs_map_values(field, value)
30
+ value.values if value.is_a?(::Hash) && field.type_instance.is_a?(Types::Hash)
31
+ end
32
+
33
+ def fs_validate_elements(field, value)
34
+ element = field.options[:element]
35
+ return unless element
36
+
37
+ if value.is_a?(::Array)
38
+ fs_validate_array_elements(field, value, element)
39
+ elsif (items = fs_map_values(field, value))
40
+ bad = items.count { |item| Restrictions.problem(item, element) }
41
+ errors.add(field.name, Types::Hash.invalid_entries_message(bad)) if bad.positive?
42
+ end
43
+ end
44
+
45
+ def fs_validate_array_elements(field, value, element)
46
+ bad = value.each_index.select { |index| Restrictions.problem(value[index], element) }
47
+ errors.add(field.name, Types::Array.invalid_elements_message(bad)) unless bad.empty?
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,199 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ # A format-neutral, read-only walk of a struct's fields for code that exports a struct to another schema
5
+ # language. The walk reports declarations and nothing else: policy (null, defaults, pass-through options,
6
+ # type mapping) belongs to the exporter. Nodes keep the type instance and options they came from.
7
+ module Introspection
8
+ # One field with its external key and its node.
9
+ class Property
10
+ # @return [FieldStruct::Field]
11
+ attr_reader :field
12
+ # @return [String] the external name for the chosen serialization
13
+ attr_reader :key
14
+ # @return [ScalarNode, ArrayNode, MapNode, UnionNode, StructNode]
15
+ attr_reader :node
16
+
17
+ # @param field [FieldStruct::Field]
18
+ # @param key [String]
19
+ # @param node [ScalarNode, ArrayNode, MapNode, UnionNode, StructNode]
20
+ def initialize(field, key, node)
21
+ @node = node
22
+ @key = key
23
+ @field = field
24
+ freeze
25
+ end
26
+ end
27
+
28
+ # A scalar (or any non-composite) type with the options it is checked with.
29
+ class ScalarNode
30
+ # @return [FieldStruct::Types::Base]
31
+ attr_reader :type
32
+ # @return [Hash{Symbol=>Object, nil}] read-only
33
+ attr_reader :options
34
+
35
+ # @param type [FieldStruct::Types::Base]
36
+ # @param options [Hash{Symbol=>Object, nil}]
37
+ def initialize(type, options)
38
+ @options = options
39
+ @type = type
40
+ freeze
41
+ end
42
+ end
43
+
44
+ # An array; its element node is built on first read.
45
+ class ArrayNode
46
+ # @return [FieldStruct::Types::Array]
47
+ attr_reader :type
48
+ # @return [Hash{Symbol=>Object, nil}] the options the array was declared with; +{}+ for an array inside an array or union
49
+ attr_reader :options
50
+
51
+ # @param type [FieldStruct::Types::Array]
52
+ # @param options [Hash{Symbol=>Object, nil}]
53
+ # @param element_builder [Proc] returns the element node or nil; called at most once
54
+ def initialize(type, options, element_builder)
55
+ @lazy = Lazy.new(element_builder)
56
+ @options = options
57
+ @type = type
58
+ freeze
59
+ end
60
+
61
+ # @return [ScalarNode, ArrayNode, MapNode, StructNode, nil] nil when the element type is unknown or a union (FS-B146)
62
+ def element
63
+ @lazy.value
64
+ end
65
+
66
+ # Memoizes one value outside the frozen node (a frozen object cannot set an ivar later).
67
+ class Lazy
68
+ # @param builder [Proc] returns the value; called at most once
69
+ def initialize(builder)
70
+ @value = nil
71
+ @done = false
72
+ @builder = builder
73
+ end
74
+
75
+ # @return [ScalarNode, ArrayNode, MapNode, StructNode, nil]
76
+ def value
77
+ unless @done
78
+ @value = @builder.call
79
+ @done = true
80
+ end
81
+ @value
82
+ end
83
+ end
84
+ private_constant :Lazy
85
+ end
86
+
87
+ # A +:hash+ map; its value node is built on first read. Keys are always Strings.
88
+ class MapNode
89
+ # @return [FieldStruct::Types::Hash]
90
+ attr_reader :type
91
+ # @return [Hash{Symbol=>Object, nil}] the options the map was declared with
92
+ attr_reader :options
93
+
94
+ # @param type [FieldStruct::Types::Hash]
95
+ # @param options [Hash{Symbol=>Object, nil}]
96
+ # @param element_builder [Proc] returns the value node or nil; called at most once
97
+ def initialize(type, options, element_builder)
98
+ @lazy = ArrayNode.const_get(:Lazy).new(element_builder)
99
+ @options = options
100
+ @type = type
101
+ freeze
102
+ end
103
+
104
+ # @return [ScalarNode, ArrayNode, MapNode, StructNode, nil] the value node; nil when the value type is
105
+ # unknown or a union
106
+ def element
107
+ @lazy.value
108
+ end
109
+ end
110
+
111
+ # A union; one node per member.
112
+ class UnionNode
113
+ # @return [FieldStruct::Types::Union]
114
+ attr_reader :type
115
+ # @return [Array<ScalarNode, ArrayNode, UnionNode, StructNode>] frozen, in declared order
116
+ attr_reader :members
117
+
118
+ # @param type [FieldStruct::Types::Union]
119
+ # @param members [Array<ScalarNode, ArrayNode, UnionNode, StructNode>]
120
+ def initialize(type, members)
121
+ @members = members.freeze
122
+ @type = type
123
+ freeze
124
+ end
125
+ end
126
+
127
+ # A nested struct, by reference.
128
+ class StructNode
129
+ # @return [FieldStruct::Types::Nested]
130
+ attr_reader :type
131
+ # @return [Class] the struct class
132
+ attr_reader :klass
133
+
134
+ # @param type [FieldStruct::Types::Nested]
135
+ # @param klass [Class]
136
+ def initialize(type, klass)
137
+ @klass = klass
138
+ @type = type
139
+ freeze
140
+ end
141
+ end
142
+
143
+ class << self
144
+ # One Property per field of +klass+, in declaration order.
145
+ #
146
+ # @param klass [Class] a +FieldStruct::Base+ subclass
147
+ # @param serialization [Symbol, String] the format whose +serialize+ mapping names the keys
148
+ # @return [Array<Property>] a new Array of new objects each call
149
+ def properties(klass, serialization: :json)
150
+ meta = klass.metadata
151
+ renames = meta.serialization(serialization)
152
+ meta.map do |field|
153
+ external = (renames[field.name] || field.name).to_s
154
+ Property.new(field, external, node(field.type_instance, field.options))
155
+ end
156
+ end
157
+
158
+ # The node for a type instance checked with an options Hash.
159
+ #
160
+ # @param type [FieldStruct::Types::Base] a type instance (any other object gives a ScalarNode)
161
+ # @param options [Hash{Symbol=>Object, nil}]
162
+ # @return [ScalarNode, ArrayNode, MapNode, UnionNode, StructNode]
163
+ def node(type, options = {})
164
+ case type
165
+ when Types::Array then ArrayNode.new(type, options, -> { element_node(options) })
166
+ when Types::Hash then MapNode.new(type, options, -> { element_node(options) })
167
+ when Types::Union then UnionNode.new(type, type.member_types.map { |member| node(member) })
168
+ when Types::Nested then StructNode.new(type, type.struct_class)
169
+ else ScalarNode.new(type, options)
170
+ end
171
+ end
172
+
173
+ # Whether the class can serve as a definition key or title.
174
+ #
175
+ # @param klass [Class]
176
+ # @return [Boolean] false for anonymous classes and classes under an anonymous module
177
+ def named?(klass)
178
+ label = klass.name
179
+ return false if label.nil?
180
+
181
+ !label.include?('#<')
182
+ end
183
+
184
+ private
185
+
186
+ def element_node(options)
187
+ declared = options[:of_type]
188
+ return if declared.nil?
189
+
190
+ if declared.is_a?(::Class)
191
+ return if declared <= Types::Union
192
+
193
+ declared = declared.new
194
+ end
195
+ node(declared, options[:element] || {})
196
+ end
197
+ end
198
+ end
199
+ end