Class: Parametric::OneOf

Inherits:
Object
  • Object
show all
Defined in:
lib/parametric/one_of.rb

Overview

Policy that validates a value against multiple schemas and chooses the first valid match.

OneOf is useful for polymorphic validation where a field can be one of several different object structures. It tries each schema in order and returns the output of the first schema that successfully validates the input.

Examples:

Basic usage

user_schema = Schema.new { field(:name).type(:string).present }
admin_schema = Schema.new { field(:role).type(:string).options(['admin']) }

schema = Schema.new do |sc, _|
  sc.field(:person).type(:object).one_of(user_schema, admin_schema)
end

With Struct

class MyStruct
  include Parametric::Struct

  schema do
    field(:data).type(:object).one_of(schema1, schema2, schema3)
  end
end

Defined Under Namespace

Classes: Runner

Instance Method Summary collapse

Constructor Details

#initialize(schemas = []) ⇒ OneOf

Initialize with an array of schemas to validate against

Parameters:

  • schemas (Array<Schema>) (defaults to: [])

    Array of Parametric::Schema objects



30
31
32
# File 'lib/parametric/one_of.rb', line 30

def initialize(schemas = [])
  @schemas = schemas
end

Instance Method Details

#build(key, value, payload:, context:) ⇒ Runner

Build a Runner instance for this policy (PolicyFactory interface)

Parameters:

  • key (Symbol)

    The field key being validated

  • value (Object)

    The value to validate

  • payload (Hash)

    The full input payload

  • context (Object)

    Validation context

Returns:

  • (Runner)

    A new Runner instance



41
42
43
# File 'lib/parametric/one_of.rb', line 41

def build(key, value, payload:, context:)
  Runner.new(@schemas, key, value, payload, context)
end

#meta_dataHash

Return metadata about this policy

Returns:

  • (Hash)

    Metadata hash with type and schema information



48
49
50
# File 'lib/parametric/one_of.rb', line 48

def 
  { type: :object, schema: @schemas }
end