Class: Monads::Result

Inherits:
Object
  • Object
show all
Includes:
Monad
Defined in:
lib/ruby-monads/result.rb

Direct Known Subclasses

Failure, Success

Constant Summary collapse

FAILURE_TRIGGER =
StandardError

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Monad

#fmap, included, #initialize, #join, #method_missing

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Monads::Monad

Class Method Details

.unit(value) ⇒ Object

unit

a -> M a



8
9
10
11
12
13
14
15
16
# File 'lib/ruby-monads/result.rb', line 8

def self.unit(value)
  if value.is_a?(FAILURE_TRIGGER) || value.is_a?(Failure)
    Failure.new(value)
  else
    Success.new(value)
  end
rescue => error
  Failure.new(error)
end

Instance Method Details

#bind(&block) ⇒ Object

bind

(a -> M b) -> M a -> M b



19
20
21
22
23
24
25
26
27
# File 'lib/ruby-monads/result.rb', line 19

def bind(&block)
  return self if is_a?(Failure)

  begin
    ensure_monadic_result(&block).call
  rescue FAILURE_TRIGGER => error
    Failure.new(error)
  end
end

#unwrap(default_value = @value) ⇒ Object

unwrap

a -> M a -> a



30
31
32
# File 'lib/ruby-monads/result.rb', line 30

def unwrap(default_value = @value)
  is_a?(Failure) ? default_value : @value
end