Class: Parametric::Wrapper

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

Overview

A policy wrapper that delegates type coercion and validation to external objects.

This allows integration of custom types, domain objects, or value objects that implement their own coercion and validation logic into Parametric schemas.

The wrapped object must implement:

  • ‘coerce(value)`: Method to convert input values to the desired type

  • The returned object must have an ‘errors` method that returns validation errors

Examples:

Basic usage

Money = Data.define(:amount, :currency) do
  def self.coerce(value)
    case value
    when Hash
      new(value[:amount], value[:currency])
    when String
      parts = value.split(' ')
      new(parts[0].to_f, parts[1])
    else
      new(value, 'USD')
    end
  end

  def errors
    errors = {}
    errors[:amount] = ['must be positive'] if amount <= 0
    errors[:currency] = ['invalid'] unless %w[USD EUR GBP].include?(currency)
    errors
  end
end

field(:price).wrap(Money)

See Also:

Defined Under Namespace

Classes: Runner

Instance Method Summary collapse

Constructor Details

#initialize(caster) ⇒ Wrapper

Initialize the wrapper with a caster object.



42
43
44
# File 'lib/parametric/wrapper.rb', line 42

def initialize(caster)
  @caster = caster
end

Instance Method Details

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

Build a policy runner for this wrapper.



53
54
55
# File 'lib/parametric/wrapper.rb', line 53

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

#meta_dataHash

Return metadata about this policy.



60
61
62
# File 'lib/parametric/wrapper.rb', line 60

def 
  { type: @caster }
end