Module: Dry::Monads::Do::Mixin

Included in:
Dry::Monads::Do
Defined in:
lib/dry/monads/do/mixin.rb

Overview

Do notation as a mixin. You can use it in any place in your code, see examples.

Examples:

class-level mixin


class CreateUser
  extend Dry::Monads::Do::Mixin
  extend Dry::Monads[:result]

  def self.run(params)
    self.call do
      values = bind Validator.validate(params)
      user = bind UserRepository.create(values)

      Success(user)
    end
  end
end

using methods defined on Do


create_user = proc do |params|
  Do.() do
    values = bind validate(params)
    user = bind user_repo.create(values)

    Success(user)
  end
end

Instance Method Summary collapse

Instance Method Details

#bind(monads) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/dry/monads/do/mixin.rb', line 46

def bind(monads)
  monads = Do.coerce_to_monad(Array(monads))
  unwrapped = monads.map do |result|
    monad = result.to_monad
    monad.or { Do.halt(monad) }.value!
  end
  monads.size == 1 ? unwrapped[0] : unwrapped
end

#callObject



39
40
41
42
43
# File 'lib/dry/monads/do/mixin.rb', line 39

def call
  yield
rescue Halt => e
  e.result
end