Class: Parametric::OneOf::Runner

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(schemas, key, value, payload, context) ⇒ Runner

Initialize the runner with validation parameters

Parameters:

  • schemas (Array<Schema>)

    Schemas to validate against

  • key (Symbol)

    Field key being validated

  • value (Object)

    Value to validate

  • payload (Hash)

    Full input payload

  • context (Object)

    Validation context



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 = []
  @message = nil
end

Instance Method Details

#eligible?Boolean

Should this policy run at all? returning [false] halts the field policy chain.

Returns:

  • (Boolean)


78
79
80
# File 'lib/parametric/one_of.rb', line 78

def eligible?
  true
end

#messageString?

Error message when validation fails

Returns:

  • (String, nil)

    Error message if validation failed, nil if valid



120
121
122
# File 'lib/parametric/one_of.rb', line 120

def message
  @message
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)

Returns:

  • (Boolean)

    true if exactly one schema validates the input



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
    @message = "#{@raw_value} is invalid. Multiple valid sub-schemas found"
  elsif valids.empty?
    @message = "#{@raw_value} is invalid. No valid sub-schema found"
  end
  @message.nil?
end

#valueObject

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.

Returns:

  • (Object)

    The coerced value from the first valid schema, or raw value if none match



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