Class: RSchema::Schemas::Coercer

Inherits:
Object
  • Object
show all
Defined in:
lib/rschema/schemas/coercer.rb

Overview

A schema that applies a coercer to a value, before passing the coerced value to a subschema.

This is not a type of schema that you would typically create yourself. It is used internally to implement RSchema’s coercion functionality.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(coercer, subschema) ⇒ Coercer

Returns a new instance of Coercer.



14
15
16
17
18
# File 'lib/rschema/schemas/coercer.rb', line 14

def initialize(coercer, subschema)
  byebug if coercer.is_a?(Array)
  @coercer = coercer
  @subschema = subschema
end

Instance Attribute Details

#coercerObject (readonly)

Returns the value of attribute coercer.



12
13
14
# File 'lib/rschema/schemas/coercer.rb', line 12

def coercer
  @coercer
end

#subschemaObject (readonly)

Returns the value of attribute subschema.



12
13
14
# File 'lib/rschema/schemas/coercer.rb', line 12

def subschema
  @subschema
end

Instance Method Details

#call(value, options) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rschema/schemas/coercer.rb', line 20

def call(value, options)
  unless coercer.will_affect?(value)
    # short-circuit the coercer
    return @subschema.call(value, options)
  end

  result = coercer.call(value)
  if result.valid?
    @subschema.call(result.value, options)
  else
    failure(value, result.error)
  end
end

#with_wrapped_subschemas(wrapper) ⇒ Object



34
35
36
# File 'lib/rschema/schemas/coercer.rb', line 34

def with_wrapped_subschemas(wrapper)
  self.class.new(coercer, wrapper.wrap(subschema))
end