Class: RSchema::Schemas::Sum

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

Overview

A schema that represents a "sum type"

Values must conform to one of the subschemas.

Examples:

A schema that matches both Integers and Strings

schema = RSchema.define { either(_String, _Integer) }
schema.valid?("hello") #=> true
schema.valid?(5) #=> true

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subschemas) ⇒ Sum

Returns a new instance of Sum.


18
19
20
# File 'lib/rschema/schemas/sum.rb', line 18

def initialize(subschemas)
  @subschemas = subschemas
end

Instance Attribute Details

#subschemasObject (readonly)

Returns the value of attribute subschemas


16
17
18
# File 'lib/rschema/schemas/sum.rb', line 16

def subschemas
  @subschemas
end

Instance Method Details

#call(value, options) ⇒ Object


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

def call(value, options)
  suberrors = []

  @subschemas.each do |ss|
    result = ss.call(value, options)
    return result if result.valid?
    suberrors << result.error
  end

  Result.failure(suberrors)
end

#with_wrapped_subschemas(wrapper) ⇒ Object


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

def with_wrapped_subschemas(wrapper)
  wrapped_subschemas = subschemas.map { |ss| wrapper.wrap(ss) }
  self.class.new(wrapped_subschemas)
end