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


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

def initialize(subschemas)
  @subschemas = subschemas
end

Instance Attribute Details

#subschemasObject (readonly)

Returns the value of attribute subschemas


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

def subschemas
  @subschemas
end

Instance Method Details

#call(value, options) ⇒ Object


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

def call(value, options)
  suberrors = []

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

  Result.failure(suberrors)
end

#with_wrapped_subschemas(wrapper) ⇒ Object


36
37
38
39
# File 'lib/rschema/schemas/sum.rb', line 36

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