Class: Parametric::OneOf::Runner
- Inherits:
-
Object
- Object
- Parametric::OneOf::Runner
- Defined in:
- lib/parametric/one_of.rb
Overview
Runner handles the actual validation logic for OneOf policy.
It validates the input value against each schema in order and determines which one(s) are valid. The policy succeeds if exactly one schema validates the input, and fails if zero or multiple schemas are valid.
Instance Method Summary collapse
-
#eligible? ⇒ Boolean
Should this policy run at all? returning [false] halts the field policy chain.
-
#initialize(schemas, key, value, payload, context) ⇒ Runner
constructor
Initialize the runner with validation parameters.
-
#message ⇒ String?
Error message when validation fails.
-
#valid? ⇒ Boolean
Validates that exactly one schema matches the input value.
-
#value ⇒ Object
Returns the validated and coerced value from the first matching schema.
Constructor Details
#initialize(schemas, key, value, payload, context) ⇒ Runner
Initialize the runner with validation parameters
65 66 67 68 69 70 71 72 73 |
# File 'lib/parametric/one_of.rb', line 65 def initialize(schemas, key, value, payload, context) @schemas = schemas @key = key @raw_value = value @payload = payload @context = context @results = [] = nil end |
Instance Method Details
#eligible? ⇒ Boolean
Should this policy run at all? returning [false] halts the field policy chain.
78 79 80 |
# File 'lib/parametric/one_of.rb', line 78 def eligible? true end |
#message ⇒ String?
Error message when validation fails
120 121 122 |
# File 'lib/parametric/one_of.rb', line 120 def end |
#valid? ⇒ Boolean
Validates that exactly one schema matches the input value.
The validation fails if:
-
No schemas validate the input (invalid data)
-
Multiple schemas validate the input (ambiguous match)
89 90 91 92 93 94 95 96 97 98 |
# File 'lib/parametric/one_of.rb', line 89 def valid? value valids = @results.select(&:valid?) if valids.size > 1 = "#{@raw_value} is invalid. Multiple valid sub-schemas found" elsif valids.empty? = "#{@raw_value} is invalid. No valid sub-schema found" end .nil? end |
#value ⇒ Object
Returns the validated and coerced value from the first matching schema.
This method triggers the validation process by resolving the input value against each schema. If a valid schema is found, its coerced output is returned. Otherwise, the raw value is returned unchanged.
107 108 109 110 111 112 113 114 115 |
# File 'lib/parametric/one_of.rb', line 107 def value @value ||= begin @results = @schemas.map do |schema| schema.resolve(@raw_value) end first_valid = @results.find(&:valid?) first_valid ? first_valid.output : @raw_value end end |