Class: Dry::Data::SumType

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

Direct Known Subclasses

Optional

Defined Under Namespace

Classes: Optional

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(left, right) ⇒ SumType

Returns a new instance of SumType.



27
28
29
# File 'lib/dry/data/sum_type.rb', line 27

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

Instance Attribute Details

#leftObject (readonly)

Returns the value of attribute left.



16
17
18
# File 'lib/dry/data/sum_type.rb', line 16

def left
  @left
end

#rightObject (readonly)

Returns the value of attribute right.



18
19
20
# File 'lib/dry/data/sum_type.rb', line 18

def right
  @right
end

Instance Method Details

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



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dry/data/sum_type.rb', line 35

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

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

#nameObject



31
32
33
# File 'lib/dry/data/sum_type.rb', line 31

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

#valid?(input) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/dry/data/sum_type.rb', line 50

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