Class: Dry::Types::Sum

Inherits:
Object
  • Object
show all
Includes:
Builder, Options
Defined in:
lib/dry/types/sum.rb

Direct Known Subclasses

Constrained

Defined Under Namespace

Classes: Constrained

Instance Attribute Summary collapse

Attributes included from Options

#meta, #options

Instance Method Summary collapse

Methods included from Options

#with

Methods included from Builder

#constrained, #constrained_type, #constructor, #default, #enum, #maybe, #optional, #safe, #|

Constructor Details

#initialize(left, right, options = {}) ⇒ Sum

Returns a new instance of Sum.



19
20
21
22
23
# File 'lib/dry/types/sum.rb', line 19

def initialize(left, right, options = {})
  super
  @left, @right = left, right
  freeze
end

Instance Attribute Details

#leftObject (readonly)

Returns the value of attribute left.



9
10
11
# File 'lib/dry/types/sum.rb', line 9

def left
  @left
end

#rightObject (readonly)

Returns the value of attribute right.



11
12
13
# File 'lib/dry/types/sum.rb', line 11

def right
  @right
end

Instance Method Details

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



29
30
31
32
33
# File 'lib/dry/types/sum.rb', line 29

def call(input)
  try(input) do |result|
    raise ConstraintError, result
  end.input
end

#nameObject



25
26
27
# File 'lib/dry/types/sum.rb', line 25

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

#primitive?(value) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/dry/types/sum.rb', line 50

def primitive?(value)
  left.primitive?(value) || right.primitive?(value)
end

#try(input, &block) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/dry/types/sum.rb', line 36

def try(input, &block)
  result = left.try(input) do
    right.try(input)
  end

  return result if result.success?

  if block
    yield(result)
  else
    result
  end
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/dry/types/sum.rb', line 54

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