Class: Dry::Data::SumType

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/data/sum_type.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(left, right) ⇒ SumType

Returns a new instance of SumType.



10
11
12
# File 'lib/dry/data/sum_type.rb', line 10

def initialize(left, right)
  @left, @right = left, right
end

Instance Attribute Details

#leftObject (readonly)

Returns the value of attribute left.



6
7
8
# File 'lib/dry/data/sum_type.rb', line 6

def left
  @left
end

#rightObject (readonly)

Returns the value of attribute right.



8
9
10
# File 'lib/dry/data/sum_type.rb', line 8

def right
  @right
end

Instance Method Details

#call(input) ⇒ Object Also known as: []



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/dry/data/sum_type.rb', line 18

def call(input)
  begin
    value = left[input]

    if left.valid?(value)
      value
    else
      right[value]
    end
  rescue TypeError
    right[input]
  end
end

#nameObject



14
15
16
# File 'lib/dry/data/sum_type.rb', line 14

def name
  [left, right].map(&:name).join(' | ')
end

#valid?(input) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/dry/data/sum_type.rb', line 33

def valid?(input)
  left.valid?(input) || right.valid?(input)
end