Class: Deterministic::Either::AttemptAll

Inherits:
Object
  • Object
show all
Defined in:
lib/deterministic/either/attempt_all.rb

Defined Under Namespace

Classes: EitherExpectedError

Instance Method Summary collapse

Constructor Details

#initialize(context, &block) ⇒ AttemptAll

Returns a new instance of AttemptAll.



10
11
12
13
14
# File 'lib/deterministic/either/attempt_all.rb', line 10

def initialize(context, &block)
  @context = context || self
  @tries = []
  instance_eval(&block)
end

Instance Method Details

#call(initial = nil) ⇒ Object



16
17
18
19
20
# File 'lib/deterministic/either/attempt_all.rb', line 16

def call(initial=nil)
  result = @tries.inject(Deterministic::Success(initial)) do |acc, try|
    acc.success? ? acc << try.call(acc) : acc
  end
end

#let(sym = nil, &block) ⇒ Object

Basicly a monad



37
38
39
40
41
42
43
# File 'lib/deterministic/either/attempt_all.rb', line 37

def let(sym=nil, &block)
  @tries << ->(acc) {
    @context.instance_exec(acc.value, &block).tap do |value|
      raise EitherExpectedError, "Expected the result to be either Success or Failure" unless value.is_a? Either
    end
  }
end

#try(&block) ⇒ Object

This is a functor



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/deterministic/either/attempt_all.rb', line 23

def try(&block)
  try_p = ->(acc) {
    begin
      value = @context.instance_exec(acc.value, &block)
      Deterministic::Success(value)
    rescue => ex
      Deterministic::Failure(ex)
    end
  }

  @tries << try_p
end