Class: Dry::Monads::Maybe

Inherits:
Object
  • Object
show all
Extended by:
Core::ClassAttributes
Includes:
Transformer
Defined in:
lib/dry/monads/maybe.rb,
lib/dry/monads/result.rb

Overview

Represents a value which can exist or not, i.e. it could be nil.

Defined Under Namespace

Modules: Hash, Mixin Classes: None, Some

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Transformer

#fmap2, #fmap3

Class Method Details

.coerce(value) ⇒ Maybe::Some, Maybe::None

Wraps the given value with into a Maybe object.

Parameters:

  • value (Object)

    value to be stored in the monad

Returns:



22
23
24
25
26
27
28
# File 'lib/dry/monads/maybe.rb', line 22

def coerce(value)
  if value.nil?
    None.instance
  else
    Some.new(value)
  end
end

.pure(value = Undefined, &block) ⇒ Maybe::Some

Wraps the given value with Some.

Parameters:

  • value (Object) (defaults to: Undefined)

    value to be wrapped with Some

  • block (Object)

    block to be wrapped with Some

Returns:



36
37
38
# File 'lib/dry/monads/maybe.rb', line 36

def pure(value = Undefined, &block)
  Some.new(Undefined.default(value, block))
end

.to_procProc

Reutrns a Some wrapper converted to a block

Returns:

  • (Proc)


43
44
45
# File 'lib/dry/monads/maybe.rb', line 43

def to_proc
  @to_proc ||= method(:coerce).to_proc
end

Instance Method Details

#monadMonad

Returns the Maybe monad. This is how we're doing polymorphism in Ruby 😕

Returns:

  • (Monad)


70
# File 'lib/dry/monads/maybe.rb', line 70

def monad = Maybe

#none?Boolean Also known as: failure?

Returns true for an instance of a None monad.

Returns:

  • (Boolean)


49
# File 'lib/dry/monads/maybe.rb', line 49

def none? = is_a?(None)

#some?Boolean Also known as: success?

Returns true for an instance of a Some monad.

Returns:

  • (Boolean)


53
# File 'lib/dry/monads/maybe.rb', line 53

def some? = is_a?(Some)

#to_maybeMaybe::Some, Maybe::None

Returns self, added to keep the interface compatible with that of Either monad types.

Returns:



59
# File 'lib/dry/monads/maybe.rb', line 59

def to_maybe = self

#to_monadMaybe::Some, Maybe::None

Returns self.

Returns:



64
# File 'lib/dry/monads/maybe.rb', line 64

def to_monad = self