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.
- checksums.yaml +4 -4
- data/.claude-plugin/marketplace.json +13 -0
- data/.claude-plugin/plugin.json +9 -0
- data/AGENTS.md +47 -54
- data/CHANGELOG.md +53 -640
- data/LICENSE.txt +21 -0
- data/README.md +33 -628
- data/USAGE.md +771 -715
- data/docs/getting_started.md +139 -325
- data/lib/field_struct/base.rb +241 -1149
- data/lib/field_struct/class_macros.rb +163 -0
- data/lib/field_struct/describer.rb +167 -0
- data/lib/field_struct/errors.rb +182 -62
- data/lib/field_struct/exceptions.rb +40 -0
- data/lib/field_struct/field.rb +69 -135
- data/lib/field_struct/field_builder.rb +110 -0
- data/lib/field_struct/field_checks.rb +50 -0
- data/lib/field_struct/introspection.rb +199 -0
- data/lib/field_struct/json_codec.rb +240 -0
- data/lib/field_struct/metadata.rb +65 -260
- data/lib/field_struct/model_name.rb +27 -27
- data/lib/field_struct/option_checker.rb +121 -0
- data/lib/field_struct/partial.rb +49 -0
- data/lib/field_struct/presence.rb +45 -0
- data/lib/field_struct/rbs.rb +151 -271
- data/lib/field_struct/registered_option.rb +113 -0
- data/lib/field_struct/registry.rb +40 -50
- data/lib/field_struct/restrictions.rb +90 -0
- data/lib/field_struct/scaffold.rb +274 -301
- data/lib/field_struct/suggestion.rb +33 -0
- data/lib/field_struct/types/array.rb +147 -126
- data/lib/field_struct/types/base.rb +113 -124
- data/lib/field_struct/types/big_decimal.rb +59 -55
- data/lib/field_struct/types/binary.rb +18 -25
- data/lib/field_struct/types/boolean.rb +74 -97
- data/lib/field_struct/types/builtin.rb +32 -0
- data/lib/field_struct/types/date.rb +23 -137
- data/lib/field_struct/types/datetime.rb +30 -139
- data/lib/field_struct/types/element_options.rb +51 -0
- data/lib/field_struct/types/email.rb +27 -38
- data/lib/field_struct/types/float.rb +58 -56
- data/lib/field_struct/types/format_presets.rb +30 -0
- data/lib/field_struct/types/hash.rb +144 -0
- data/lib/field_struct/types/immutable_string.rb +16 -9
- data/lib/field_struct/types/integer.rb +74 -102
- data/lib/field_struct/types/nested.rb +57 -58
- data/lib/field_struct/types/preset_resolver.rb +9 -24
- data/lib/field_struct/types/rfc3339_format.rb +70 -153
- data/lib/field_struct/types/string.rb +48 -46
- data/lib/field_struct/types/symbol.rb +23 -20
- data/lib/field_struct/types/temporal.rb +232 -0
- data/lib/field_struct/types/time.rb +32 -145
- data/lib/field_struct/types/union.rb +111 -65
- data/lib/field_struct/types/union_pick.rb +139 -0
- data/lib/field_struct/types/url.rb +24 -35
- data/lib/field_struct/types/uuid.rb +24 -35
- data/lib/field_struct/types/value.rb +14 -9
- data/lib/field_struct/types/zone.rb +118 -0
- data/lib/field_struct/version.rb +3 -3
- data/lib/field_struct.rb +102 -122
- data/sig/field_struct.rbs +1180 -2300
- data/sig/manifest.yaml +6 -0
- data/skills/field-struct/SKILL.md +73 -159
- metadata +37 -28
- data/CODE_OF_CONDUCT.md +0 -132
- data/UPGRADING.md +0 -743
- data/lib/field_struct/error.rb +0 -48
- data/lib/field_struct/types/temporal_parser.rb +0 -93
- data/lib/field_struct/types/time_format_resolver.rb +0 -54
- data/lib/field_struct/types/zone_option.rb +0 -267
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FieldStruct
|
|
4
|
+
# The class-level configuration macros of {Base}: policies, mutability flags and cross-field validators.
|
|
5
|
+
module ClassMacros
|
|
6
|
+
# Reads or sets what happens when a value cannot be coerced. Inherited; a child's value never changes its parent.
|
|
7
|
+
#
|
|
8
|
+
# @param policy [Symbol, nil] +:keep_raw+, +:replace+ or +:raise+; omit to read
|
|
9
|
+
# @return [Symbol]
|
|
10
|
+
# @raise [ArgumentError] for any other value
|
|
11
|
+
def coercion_policy(policy = nil)
|
|
12
|
+
return inherited_setting(:@coercion_policy, :coercion_policy, :keep_raw) if policy.nil?
|
|
13
|
+
|
|
14
|
+
check_policy!(policy, Base::VALID_COERCION_POLICIES, 'coercion policy')
|
|
15
|
+
@coercion_policy = policy
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Reads or sets what happens to input keys that match no field. Inherited like {.coercion_policy}.
|
|
19
|
+
#
|
|
20
|
+
# @param policy [Symbol, nil] +:ignore+ or +:raise+; omit to read
|
|
21
|
+
# @return [Symbol]
|
|
22
|
+
# @raise [ArgumentError] for any other value
|
|
23
|
+
def unknown_attributes(policy = nil)
|
|
24
|
+
return inherited_setting(:@unknown_attributes, :unknown_attributes, :ignore) if policy.nil?
|
|
25
|
+
|
|
26
|
+
check_policy!(policy, Base::VALID_UNKNOWN_POLICIES, 'unknown_attributes policy')
|
|
27
|
+
@unknown_attributes = policy
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Reads or sets which fields +as_json+ and +to_json+ leave out. Inherited like {.coercion_policy}.
|
|
31
|
+
#
|
|
32
|
+
# @param policy [Symbol, nil] +:none+ writes every field; +:unset+ leaves out a field that was not given and is
|
|
33
|
+
# +nil+ (defaults and a given +nil+ are written); omit to read
|
|
34
|
+
# @return [Symbol]
|
|
35
|
+
# @raise [ArgumentError] for any other value
|
|
36
|
+
def json_omit(policy = nil)
|
|
37
|
+
return inherited_setting(:@json_omit, :json_omit, :none) if policy.nil?
|
|
38
|
+
|
|
39
|
+
check_policy!(policy, Base::VALID_JSON_OMIT_POLICIES, 'json_omit policy')
|
|
40
|
+
@json_omit = policy
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Refuses every setter call after construction (+ImmutableError+). One-way; inherited.
|
|
44
|
+
#
|
|
45
|
+
# @return [true]
|
|
46
|
+
def immutable!
|
|
47
|
+
@immutable = true
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Freezes instances at the end of +new+. One-way; inherited.
|
|
51
|
+
#
|
|
52
|
+
# @return [true]
|
|
53
|
+
def frozen!
|
|
54
|
+
@frozen_on_construct = true
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Marks the class as a mirror: a field of its type reads any other object into it, one public reader per declared
|
|
58
|
+
# field. One-way; inherited.
|
|
59
|
+
#
|
|
60
|
+
# @return [true]
|
|
61
|
+
def mirror!
|
|
62
|
+
@mirror = true
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# @return [Boolean] whether this class or an ancestor called {.mirror!}
|
|
66
|
+
def mirror?
|
|
67
|
+
flagged?(:@mirror, :mirror?)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# @return [Boolean] whether this class or an ancestor called {.immutable!}
|
|
71
|
+
def immutable?
|
|
72
|
+
flagged?(:@immutable, :immutable?)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# @return [Boolean] whether this class or an ancestor called {.frozen!}
|
|
76
|
+
def frozen_on_construct?
|
|
77
|
+
flagged?(:@frozen_on_construct, :frozen_on_construct?)
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Registers cross-field validators: each method name and the block is its own validator.
|
|
81
|
+
#
|
|
82
|
+
# @param method_names [Array<Symbol>] public instance methods called with no arguments
|
|
83
|
+
# @yieldparam record [FieldStruct::Base]
|
|
84
|
+
# @return [self]
|
|
85
|
+
def validate(*method_names, &block)
|
|
86
|
+
method_names.each { |method_name| validators << ->(record) { record.public_send(method_name) } }
|
|
87
|
+
validators << block if block
|
|
88
|
+
self
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# Declares the external names a format uses: internal field name to external name. Last write per format wins;
|
|
92
|
+
# mappings are inherited as a snapshot. Only +:json+ is wired into the gem; other formats are stored for other gems.
|
|
93
|
+
#
|
|
94
|
+
# @param format [Symbol, String] e.g. +:json+
|
|
95
|
+
# @param mapping [Hash{Symbol=>Symbol,String}] internal name to external name
|
|
96
|
+
# @return [self]
|
|
97
|
+
# @raise [ArgumentError] when a key is not a declared field
|
|
98
|
+
def serialize(format, **mapping)
|
|
99
|
+
mapping = mapping.to_h { |internal, external| [internal.to_sym, external.to_s] }
|
|
100
|
+
undeclared = mapping.keys.reject { |name| metadata[name] }
|
|
101
|
+
unless undeclared.empty?
|
|
102
|
+
raise ArgumentError, "serialize #{format.to_sym.inspect} references undeclared field(s): " \
|
|
103
|
+
"#{undeclared.map(&:inspect).join(', ')}. Declare fields before calling serialize."
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
metadata.add_serialization(format, mapping)
|
|
107
|
+
self
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# Builds an instance from a JSON object: parses with Oj (decimals arrive as BigDecimal), maps external names back
|
|
111
|
+
# (nested structs and arrays of them through their own mappings), then calls +new+.
|
|
112
|
+
#
|
|
113
|
+
# @param json [String]
|
|
114
|
+
# @return [FieldStruct::Base]
|
|
115
|
+
# @raise [ArgumentError] when the root is not an object
|
|
116
|
+
# @raise [EncodingError] when the JSON is malformed (the message never quotes the input)
|
|
117
|
+
def from_json(json)
|
|
118
|
+
JsonCodec.load(self, json)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# A sibling class for update (PATCH) bodies, +<Klass>::Partial+, built on the first call and the same after:
|
|
122
|
+
# every field optional with no default, the same mappings and policies, and +json_omit :unset+. Cross-field
|
|
123
|
+
# validators and methods defined on this class (reader overrides too) don't carry over.
|
|
124
|
+
#
|
|
125
|
+
# @return [Class] a direct subclass of +FieldStruct::Base+
|
|
126
|
+
# @raise [ArgumentError] when this class already has its own +Partial+ constant on the first call
|
|
127
|
+
def partial
|
|
128
|
+
@partial ||= PartialBuilder.call(self)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# @return [Array<Proc>] the validators, inherited as a copy when the subclass was created
|
|
132
|
+
def validators
|
|
133
|
+
@validators ||= []
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
private
|
|
137
|
+
|
|
138
|
+
def check_policy!(policy, allowed, label)
|
|
139
|
+
return if allowed.include?(policy)
|
|
140
|
+
|
|
141
|
+
raise ArgumentError, "unknown #{label} #{policy.inspect} (expected one of #{allowed.inspect})"
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def inherited(subclass)
|
|
145
|
+
super
|
|
146
|
+
subclass.instance_variable_set(:@metadata, Metadata.new.merge(metadata))
|
|
147
|
+
subclass.instance_variable_set(:@validators, validators.dup)
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
def inherited_setting(ivar, reader, default)
|
|
151
|
+
value = instance_variable_get(ivar)
|
|
152
|
+
return value if value
|
|
153
|
+
|
|
154
|
+
superclass.respond_to?(reader) ? superclass.public_send(reader) : default
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def flagged?(ivar, reader)
|
|
158
|
+
return true if instance_variable_get(ivar)
|
|
159
|
+
|
|
160
|
+
superclass.respond_to?(reader) ? superclass.public_send(reader) : false
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
end
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FieldStruct
|
|
4
|
+
# INTERNAL: renders fields for +Field#inspect+, +Metadata#to_h+ and +Metadata#describe+ (FS-B119, FS-B121, FS-B122).
|
|
5
|
+
module Describer
|
|
6
|
+
SEPARATOR = ' — '
|
|
7
|
+
|
|
8
|
+
module_function
|
|
9
|
+
|
|
10
|
+
# @param field [FieldStruct::Field]
|
|
11
|
+
# @return [String] +#<FieldStruct::Field :name Type flag... part...>+
|
|
12
|
+
def inspect_field(field)
|
|
13
|
+
parts = [field.name.inspect, type_label(field.type_instance)] + flags(field) + settings(field)
|
|
14
|
+
parts.concat(field.options.map { |key, value| "#{key}=#{repr(value)}" })
|
|
15
|
+
"#<#{FieldStruct.inspect_namespace}::Field #{parts.join(' ')}>"
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def flags(field)
|
|
19
|
+
[('required' if field.required?), ('nullable' if field.nullable?), ('sensitive' if field.sensitive?)].compact
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def settings(field)
|
|
23
|
+
[
|
|
24
|
+
(field.default.nil? ? nil : "default=#{field.default.inspect}"),
|
|
25
|
+
field.coercion_policy && "coercion_policy=#{field.coercion_policy.inspect}",
|
|
26
|
+
field.description && "description=#{field.description.inspect}",
|
|
27
|
+
field.rbs_type && "rbs_type=#{field.rbs_type.inspect}"
|
|
28
|
+
].compact
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# An instance's +inspect+: sensitive values masked, errors appended (FS-B115, FS-B139).
|
|
32
|
+
def inspect_instance(instance)
|
|
33
|
+
pairs = instance.class.metadata.map { |field| "#{field.name}: #{masked(instance, field)}" }
|
|
34
|
+
"#<#{instance.class.display_name} #{pairs.join(', ')}#{errors_suffix(instance.errors)}>"
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def masked(instance, field)
|
|
38
|
+
value = instance.public_send(field.name)
|
|
39
|
+
field.sensitive? && !value.nil? ? FieldStruct::FILTERED : value.inspect
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def errors_suffix(errors)
|
|
43
|
+
return '' if errors.empty?
|
|
44
|
+
|
|
45
|
+
" errors: {#{errors.to_h.map { |field, messages| "#{field}: #{messages.inspect}" }.join(', ')}}"
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# @param type [FieldStruct::Types::Base] a type instance
|
|
49
|
+
# @return [String] +String+, +Nested(Address)+ or +Union(String | Integer)+
|
|
50
|
+
def type_label(type)
|
|
51
|
+
case type
|
|
52
|
+
when Types::Nested then "Nested(#{struct_name(type.struct_class)})"
|
|
53
|
+
when Types::Union then "Union(#{type.member_types.map { |member| type_label(member) }.join(' | ')})"
|
|
54
|
+
else type.class.short_name
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# The short name of a struct class, or +AnonymousFieldStruct+.
|
|
59
|
+
def struct_name(klass)
|
|
60
|
+
klass.name ? klass.name.split('::').last : 'AnonymousFieldStruct'
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Renders an option value for +inspect+ and +describe+.
|
|
64
|
+
def repr(value)
|
|
65
|
+
case value
|
|
66
|
+
when ::Class then class_name(value)
|
|
67
|
+
when Types::Base then type_label(value)
|
|
68
|
+
when ::Hash then "{#{value.map { |key, item| "#{hash_key(key)}#{repr(item)}" }.join(', ')}}"
|
|
69
|
+
when ::Array then "[#{value.map { |item| repr(item) }.join(', ')}]"
|
|
70
|
+
else value.inspect
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def class_name(klass)
|
|
75
|
+
klass.name ? klass.name.split('::').last : 'AnonymousType'
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def hash_key(key)
|
|
79
|
+
key.is_a?(::Symbol) && key.inspect == ":#{key}" ? "#{key}: " : "#{key.inspect} => "
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# The schema view of one field (FS-B121).
|
|
83
|
+
def schema(field)
|
|
84
|
+
type = field.type_instance
|
|
85
|
+
entry = {
|
|
86
|
+
type: field.type.short_name,
|
|
87
|
+
ruby_type: [type.ruby_type].flatten.map { |klass| klass.name || klass.inspect }.join(' | '),
|
|
88
|
+
required: field.required?,
|
|
89
|
+
default: primitive(field.default),
|
|
90
|
+
options: primitive(field.options),
|
|
91
|
+
description: field.description
|
|
92
|
+
}
|
|
93
|
+
entry[:rbs_type] = field.rbs_type if field.rbs_type
|
|
94
|
+
entry[:sensitive] = true if field.sensitive?
|
|
95
|
+
entry[:nullable] = true if field.nullable?
|
|
96
|
+
entry
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def callable?(value)
|
|
100
|
+
value.respond_to?(:call)
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# Makes a value primitive for +Metadata#to_h+.
|
|
104
|
+
def primitive(value)
|
|
105
|
+
case value
|
|
106
|
+
when ::Class then class_name(value)
|
|
107
|
+
when Types::Base then value.class.short_name
|
|
108
|
+
when ::Hash, ::Array then primitive_container(value)
|
|
109
|
+
else callable?(value) ? '<callable>' : value
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def primitive_container(value)
|
|
114
|
+
value.is_a?(::Hash) ? value.to_h { |key, item| [key, primitive(item)] } : value.map { |item| primitive(item) }
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# One +describe+ line (FS-B122).
|
|
118
|
+
def describe_field(field)
|
|
119
|
+
head = [label(field), field.required? ? 'required' : 'optional', ('nullable' if field.nullable?),
|
|
120
|
+
('sensitive' if field.sensitive?)].compact
|
|
121
|
+
segments = [" #{field.name} (#{head.join(', ')})", field.description&.inspect, declared_text(field),
|
|
122
|
+
accepts_segment(field), element_segment(field)]
|
|
123
|
+
segments.compact.join(SEPARATOR)
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def declared_text(field)
|
|
127
|
+
declared = field.options.compact
|
|
128
|
+
declared.map { |key, value| "#{key}: #{repr(value)}" }.join(', ') unless declared.empty?
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def accepts_segment(field)
|
|
132
|
+
text = accepts_text(field.type)
|
|
133
|
+
"accepts #{text}" unless text.empty?
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def element_segment(field)
|
|
137
|
+
names = element_names(field)
|
|
138
|
+
"element accepts #{names.join(', ')}" if composite?(field.type_instance) && !names.empty?
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def composite?(type)
|
|
142
|
+
type.is_a?(Types::Array) || type.is_a?(Types::Hash)
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def label(field)
|
|
146
|
+
type = field.type_instance
|
|
147
|
+
return field.type.short_name unless type.is_a?(Types::Nested) && type.struct_class.name
|
|
148
|
+
|
|
149
|
+
struct_name(type.struct_class)
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def accepts_text(type_class)
|
|
153
|
+
type_class.option_schema.map do |name, descriptor|
|
|
154
|
+
shapes = descriptor[:type].map { |klass| klass.name.split('::').last }.join(' | ')
|
|
155
|
+
shapes += "; presets: #{descriptor[:presets].join(', ')}" unless descriptor[:presets].empty?
|
|
156
|
+
"#{name}#{'*' if descriptor[:required]} (#{shapes})"
|
|
157
|
+
end.join(', ')
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def element_names(field)
|
|
161
|
+
of_type = field.options[:of_type]
|
|
162
|
+
return [] unless of_type
|
|
163
|
+
|
|
164
|
+
Types::Array.element_class(of_type).option_schema.keys.map(&:to_s)
|
|
165
|
+
end
|
|
166
|
+
end
|
|
167
|
+
end
|
data/lib/field_struct/errors.rb
CHANGED
|
@@ -1,103 +1,223 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module FieldStruct
|
|
4
|
-
# Per-
|
|
5
|
-
#
|
|
6
|
-
# Shaped after ActiveModel::Errors but reuses none of its code. Each
|
|
7
|
-
# FieldStruct instance gets its own Errors object; the setter pipeline
|
|
8
|
-
# clears and rewrites a field's entry on every assignment.
|
|
4
|
+
# Per-field validation messages. A plain value object; keys are Symbols.
|
|
9
5
|
class Errors
|
|
10
|
-
|
|
6
|
+
# @param owner [FieldStruct::Base, nil] the struct these errors belong to; +paths+ walks it (FS-B40a)
|
|
7
|
+
def initialize(owner = nil)
|
|
11
8
|
@messages = {}
|
|
9
|
+
@owner = owner
|
|
10
|
+
@origins = nil
|
|
12
11
|
end
|
|
13
12
|
|
|
14
|
-
#
|
|
15
|
-
#
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
# @param source [self] the collection being copied
|
|
19
|
-
# @return [void]
|
|
20
|
-
def initialize_copy(source)
|
|
21
|
-
super
|
|
22
|
-
@messages = source.to_h.transform_values(&:dup)
|
|
13
|
+
# @param field [Symbol, String]
|
|
14
|
+
# @return [Array<String>] the field's messages, or a throwaway empty Array
|
|
15
|
+
def [](field)
|
|
16
|
+
@messages.fetch(field.to_sym) { [] }
|
|
23
17
|
end
|
|
24
18
|
|
|
25
|
-
#
|
|
26
|
-
#
|
|
27
|
-
|
|
28
|
-
@messages[field_name.to_sym] || []
|
|
29
|
-
end
|
|
30
|
-
|
|
31
|
-
# @param field_name [Symbol, String]
|
|
19
|
+
# Appends a message for a field.
|
|
20
|
+
#
|
|
21
|
+
# @param field [Symbol, String]
|
|
32
22
|
# @param message [String]
|
|
33
|
-
# @return [Array<String>] the field's
|
|
34
|
-
def add(
|
|
35
|
-
|
|
36
|
-
(@messages[key] ||= []) << message
|
|
23
|
+
# @return [Array<String>] the field's messages
|
|
24
|
+
def add(field, message)
|
|
25
|
+
(@messages[field.to_sym] ||= []) << message
|
|
37
26
|
end
|
|
38
27
|
|
|
39
|
-
#
|
|
28
|
+
# Removes all messages for a field.
|
|
40
29
|
#
|
|
41
|
-
# @param
|
|
42
|
-
# @return [
|
|
43
|
-
def clear(
|
|
44
|
-
@messages.delete(
|
|
30
|
+
# @param field [Symbol, String]
|
|
31
|
+
# @return [nil]
|
|
32
|
+
def clear(field)
|
|
33
|
+
@messages.delete(field.to_sym)
|
|
45
34
|
nil
|
|
46
35
|
end
|
|
47
36
|
|
|
48
|
-
#
|
|
37
|
+
# Freezes the messages too, so +add+ and +clear+ raise +FrozenError+; a +dup+ owns unfrozen copies.
|
|
38
|
+
#
|
|
39
|
+
# @return [self]
|
|
40
|
+
def freeze
|
|
41
|
+
@messages.each_value(&:freeze).freeze
|
|
42
|
+
@origins&.freeze
|
|
43
|
+
super
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# @return [Boolean] true when no field has a message
|
|
49
47
|
def empty?
|
|
50
|
-
# A block loop, not each_value.all?: that builds an Enumerator per call,
|
|
51
|
-
# and every validity check asks this.
|
|
52
48
|
@messages.each_value { |messages| return false unless messages.empty? }
|
|
53
49
|
true
|
|
54
50
|
end
|
|
55
51
|
|
|
56
|
-
# @return [Hash{Symbol=>Array<String>}]
|
|
57
|
-
# skipping fields with empty message lists
|
|
52
|
+
# @return [Hash{Symbol=>Array<String>}] only fields that have messages
|
|
58
53
|
def to_h
|
|
59
|
-
|
|
54
|
+
present.transform_values(&:dup)
|
|
60
55
|
end
|
|
61
|
-
alias messages to_h
|
|
62
56
|
|
|
63
|
-
#
|
|
64
|
-
# humanized field name prepended to each message. Messages on +:base+
|
|
65
|
-
# (the cross-field convention) pass through unprefixed — they are
|
|
66
|
-
# already complete sentences. Order follows field insertion order, then
|
|
67
|
-
# message order within a field.
|
|
57
|
+
# Same as {#to_h}.
|
|
68
58
|
#
|
|
69
|
-
#
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
def full_messages
|
|
74
|
-
to_h.flat_map do |field, msgs|
|
|
75
|
-
next msgs if field == :base
|
|
59
|
+
# @return [Hash{Symbol=>Array<String>}]
|
|
60
|
+
def messages
|
|
61
|
+
to_h
|
|
62
|
+
end
|
|
76
63
|
|
|
77
|
-
|
|
78
|
-
|
|
64
|
+
# @return [Array<String>] humanized field name plus message; +:base+ is unprefixed
|
|
65
|
+
def full_messages
|
|
66
|
+
present.flat_map do |field, messages|
|
|
67
|
+
field == :base ? messages.dup : messages.map { |message| "#{humanize(field)} #{message}" }
|
|
79
68
|
end
|
|
80
69
|
end
|
|
81
70
|
|
|
82
71
|
# @return [String]
|
|
83
72
|
def inspect
|
|
84
|
-
|
|
85
|
-
|
|
73
|
+
pairs = present.map { |field, messages| "#{field}=#{messages.inspect}" }
|
|
74
|
+
"#<#{FieldStruct.inspect_namespace}::Errors #{pairs.empty? ? 'empty' : pairs.join(' ')}>"
|
|
75
|
+
end
|
|
86
76
|
|
|
87
|
-
|
|
88
|
-
|
|
77
|
+
# Where each message comes from, nested structs included (FS-B40a). Walks the owner's current values and runs no
|
|
78
|
+
# validators; +to_h+ is unchanged.
|
|
79
|
+
#
|
|
80
|
+
# @return [Hash{String=>Array<String>}] a new Hash each call, e.g. +{"parts[1].code" => ["is required"]}+
|
|
81
|
+
def paths
|
|
82
|
+
out = {}
|
|
83
|
+
seen = {}.compare_by_identity
|
|
84
|
+
seen[@owner] = true if @owner
|
|
85
|
+
walk(out, '', seen)
|
|
86
|
+
out
|
|
89
87
|
end
|
|
90
88
|
|
|
91
|
-
|
|
89
|
+
# Copies every message of +other+ and remembers +other+'s owner as the origin of those keys, so +paths+ walks it.
|
|
90
|
+
#
|
|
91
|
+
# @api private
|
|
92
|
+
# @param other [FieldStruct::Errors]
|
|
93
|
+
# @return [self]
|
|
94
|
+
def absorb(other)
|
|
95
|
+
other.present.each do |field, messages|
|
|
96
|
+
messages.each { |message| add(field, message) }
|
|
97
|
+
origin = other.origin_for(field)
|
|
98
|
+
(@origins ||= {})[field] = origin if origin && !origin.equal?(@owner)
|
|
99
|
+
end
|
|
100
|
+
self
|
|
101
|
+
end
|
|
92
102
|
|
|
93
|
-
#
|
|
94
|
-
# underscores become spaces and the first character is upcased.
|
|
95
|
-
# Deliberately minimal — no inflection, no +_id+ stripping, no i18n.
|
|
103
|
+
# A copy owned by +owner+ (what +dup+ of a struct gives its copy).
|
|
96
104
|
#
|
|
105
|
+
# @api private
|
|
106
|
+
# @param owner [FieldStruct::Base]
|
|
107
|
+
# @return [FieldStruct::Errors]
|
|
108
|
+
def copy_for(owner)
|
|
109
|
+
dup.rehome(owner)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
protected
|
|
113
|
+
|
|
114
|
+
# @param owner [FieldStruct::Base]
|
|
115
|
+
# @return [self] with +owner+ as the struct +paths+ walks
|
|
116
|
+
def rehome(owner)
|
|
117
|
+
@owner = owner
|
|
118
|
+
self
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# @return [Hash{Symbol=>Array<String>}] the fields that have messages
|
|
122
|
+
def present
|
|
123
|
+
@messages.reject { |_field, messages| messages.empty? }
|
|
124
|
+
end
|
|
125
|
+
|
|
97
126
|
# @param field [Symbol]
|
|
98
|
-
# @return [
|
|
127
|
+
# @return [FieldStruct::Base, nil] the struct whose value +field+ names
|
|
128
|
+
def origin_for(field)
|
|
129
|
+
@origins&.[](field) || @owner
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# Appends this object's paths under +prefix+ to +out+.
|
|
133
|
+
#
|
|
134
|
+
# @param out [Hash{String=>Array<String>}]
|
|
135
|
+
# @param prefix [String] '' at the root
|
|
136
|
+
# @param seen [Hash{FieldStruct::Base=>Boolean}] structs already walked (compared by identity)
|
|
137
|
+
# @return [void]
|
|
138
|
+
def walk(out, prefix, seen)
|
|
139
|
+
present.each do |field, messages|
|
|
140
|
+
path = path_for(prefix, field)
|
|
141
|
+
rest = expand(out, field, messages, path, seen)
|
|
142
|
+
(out[path] ||= []).concat(rest) unless rest.empty?
|
|
143
|
+
end
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# Walks the structs that account for an "is invalid" on +field+.
|
|
147
|
+
#
|
|
148
|
+
# @param out [Hash{String=>Array<String>}]
|
|
149
|
+
# @param field [Symbol]
|
|
150
|
+
# @param messages [Array<String>]
|
|
151
|
+
# @param path [String]
|
|
152
|
+
# @param seen [Hash{FieldStruct::Base=>Boolean}]
|
|
153
|
+
# @return [Array<String>] the messages left for the field's own path
|
|
154
|
+
def expand(out, field, messages, path, seen)
|
|
155
|
+
index = messages.index('is invalid')
|
|
156
|
+
children = index ? children_of(origin_for(field), field, path, seen) : []
|
|
157
|
+
return messages.dup if index.nil? || children.empty?
|
|
158
|
+
|
|
159
|
+
children.each { |child, child_path| child.errors.walk(out, child_path, seen) }
|
|
160
|
+
messages.dup.tap { |rest| rest.delete_at(index) }
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# The nested structs under +owner+'s +field+ that have errors right now, with their paths; each is marked seen.
|
|
164
|
+
#
|
|
165
|
+
# @param owner [FieldStruct::Base, nil]
|
|
166
|
+
# @param field [Symbol]
|
|
167
|
+
# @param path [String]
|
|
168
|
+
# @param seen [Hash{FieldStruct::Base=>Boolean}]
|
|
169
|
+
# @return [Array<Array(FieldStruct::Base, String)>]
|
|
170
|
+
def children_of(owner, field, path, seen)
|
|
171
|
+
declared = owner && owner.class.metadata[field]
|
|
172
|
+
return [] unless declared
|
|
173
|
+
|
|
174
|
+
value = owner.instance_variable_get(declared.ivar_name)
|
|
175
|
+
pairs = child_pairs(value, declared, path)
|
|
176
|
+
pairs.select { |item, _| item.is_a?(Base) && claim(item, seen) }
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# Each candidate child with its path: Array elements by index, a +:hash+ field's values by quoted key.
|
|
180
|
+
#
|
|
181
|
+
# @param value [Object]
|
|
182
|
+
# @param field [FieldStruct::Field]
|
|
183
|
+
# @param path [String]
|
|
184
|
+
# @return [Array<Array(Object, String)>]
|
|
185
|
+
def child_pairs(value, field, path)
|
|
186
|
+
return value.each_with_index.map { |item, index| [item, "#{path}[#{index}]"] } if value.is_a?(::Array)
|
|
187
|
+
return [[value, path]] unless value.is_a?(::Hash) && field.type_instance.is_a?(Types::Hash)
|
|
188
|
+
|
|
189
|
+
value.map { |key, item| [item, "#{path}{#{Oj.dump(key.to_s, mode: :compat)}}"] }
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# @param item [FieldStruct::Base]
|
|
193
|
+
# @param seen [Hash{FieldStruct::Base=>Boolean}]
|
|
194
|
+
# @return [Boolean] true when +item+ has errors and was not walked yet; marks it seen
|
|
195
|
+
def claim(item, seen)
|
|
196
|
+
return false if item.errors.empty? || seen[item]
|
|
197
|
+
|
|
198
|
+
seen[item] = true
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
private
|
|
202
|
+
|
|
203
|
+
def initialize_copy(source)
|
|
204
|
+
super
|
|
205
|
+
@messages = source.instance_variable_get(:@messages).transform_values(&:dup)
|
|
206
|
+
@origins = @origins&.dup
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
# @param prefix [String]
|
|
210
|
+
# @param field [Symbol]
|
|
211
|
+
# @return [String] the path of +field+ under +prefix+; +:base+ is the prefix itself, or "base" at the root
|
|
212
|
+
def path_for(prefix, field)
|
|
213
|
+
return (prefix.empty? ? 'base' : prefix) if field == :base
|
|
214
|
+
|
|
215
|
+
prefix.empty? ? field.to_s : "#{prefix}.#{field}"
|
|
216
|
+
end
|
|
217
|
+
|
|
99
218
|
def humanize(field)
|
|
100
|
-
field.to_s.tr('_', ' ')
|
|
219
|
+
text = field.to_s.tr('_', ' ')
|
|
220
|
+
text.empty? ? text : text[0].upcase + text[1..]
|
|
101
221
|
end
|
|
102
222
|
end
|
|
103
223
|
end
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FieldStruct
|
|
4
|
+
# Root of every error FieldStruct raises itself.
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
# Raised by a setter under +coercion_policy :raise+.
|
|
8
|
+
class CoercionError < Error
|
|
9
|
+
# @return [Symbol, nil] the field that refused the value
|
|
10
|
+
attr_reader :field_name
|
|
11
|
+
|
|
12
|
+
# @return [Exception, nil] the coercion exception
|
|
13
|
+
attr_reader :original
|
|
14
|
+
|
|
15
|
+
# @param message [String]
|
|
16
|
+
# @param field_name [Symbol, nil]
|
|
17
|
+
# @param original [Exception, nil]
|
|
18
|
+
def initialize(message = nil, field_name: nil, original: nil)
|
|
19
|
+
@original = original
|
|
20
|
+
@field_name = field_name
|
|
21
|
+
super(message)
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Raised by a setter on an +immutable!+ instance after construction.
|
|
26
|
+
class ImmutableError < Error; end
|
|
27
|
+
|
|
28
|
+
# Raised under +unknown_attributes :raise+.
|
|
29
|
+
class UnknownAttributeError < Error
|
|
30
|
+
# @return [Array<Symbol>] the unknown keys, in input order
|
|
31
|
+
attr_reader :keys
|
|
32
|
+
|
|
33
|
+
# @param message [String]
|
|
34
|
+
# @param keys [Array<Symbol>]
|
|
35
|
+
def initialize(message = nil, keys: [])
|
|
36
|
+
@keys = keys
|
|
37
|
+
super(message)
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|