Class: Dry::Monads::Lazy

Inherits:
Task
  • Object
show all
Defined in:
lib/dry/monads/lazy.rb

Overview

Lazy is a twin of Task which is always executed on the current thread. The underlying mechanism provided by concurrent-ruby ensures the given computation is evaluated not more than once (compare with the built-in lazy assignement ||= which does not guarantee this).

Defined Under Namespace

Modules: Mixin

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Task

#==, [], #apply, #bind, #complete?, #discard, #fmap, #initialize, #monad, #or, #or_fmap, pure, #to_maybe, #to_monad, #to_result, #value_or, #wait

Constructor Details

This class inherits a constructor from Dry::Monads::Task

Class Method Details

.new(promise = nil, &block) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/dry/monads/lazy.rb', line 14

def new(promise = nil, &block)
  if promise
    super(promise)
  else
    super(Concurrent::Promise.new(executor: :immediate, &block))
  end
end

Instance Method Details

#forceLazy

Forces the computation. Note that if the computation thrown an error it won't be re-raised as opposed to value!/force!.

Returns:



37
38
39
40
# File 'lib/dry/monads/lazy.rb', line 37

def force
  @promise.execute
  self
end

#to_sString Also known as: inspect

Returns:

  • (String)


43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/dry/monads/lazy.rb', line 43

def to_s
  state = case promise.state
          when :fulfilled
            value!.inspect
          when :rejected
            "!#{ promise.reason.inspect }"
          else
            '?'
          end

  "Lazy(#{ state })"
end

#value!Object Also known as: force!

Forces the compution and returns its value.

Returns:

  • (Object)


28
29
30
# File 'lib/dry/monads/lazy.rb', line 28

def value!
  @promise.execute.value!
end