Class: Flows::Contract::Either

Inherits:
Flows::Contract show all
Defined in:
lib/flows/contract/either.rb

Overview

Allows to combine two or more contracts with "or" logic.

First matching contract from provided list will be used.

Examples:

str_or_sym = Flows::Contract::Either.new(String, Symbol)

str_or_sym === 'AAA'
# => true

str_or_sym === :AAA
# => true

str_or_sym === 111
# => false

Since:

  • 0.4.0

Instance Method Summary collapse

Methods inherited from Flows::Contract

#===, #check, make, #to_proc, #transform

Constructor Details

#initialize(*contracts) ⇒ Either

Returns a new instance of Either.

Parameters:

  • contracts (Array<Contract, Object>)

    contract list. Non-contract elements will be wrapped with CaseEq.

Since:

  • 0.4.0



20
21
22
23
24
# File 'lib/flows/contract/either.rb', line 20

def initialize(*contracts)
  raise 'Contract list must not be empty' if contracts.length.zero?

  @contracts = contracts.map(&method(:to_contract))
end

Instance Method Details

#check!(other) ⇒ Object

Raises:

See Also:

Since:

  • 0.4.0



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/flows/contract/either.rb', line 27

def check!(other)
  errors = @contracts.each_with_object([]) do |con, errs|
    result = con.check(other)

    return true if result.ok?

    errs << result.error
  end

  raise Error.new(other, errors.join("\nOR "))
end

#transform!(other) ⇒ Object

Raises:

See Also:

Since:

  • 0.4.0



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/flows/contract/either.rb', line 40

def transform!(other)
  errors = @contracts.each_with_object([]) do |con, errs|
    result = con.transform(other)

    return result.unwrap if result.ok?

    errs << result.error
  end

  raise Error.new(other, errors.join("\nOR "))
end