Class: Monadic::Either Abstract

Inherits:
Object show all
Includes:
Monad
Defined in:
lib/monadic/either.rb

Overview

This class is abstract.

Chains function calls and stops executing if one of them fails.

Direct Known Subclasses

Failure, Success

Defined Under Namespace

Classes: Chain

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Monad

#==, #flat_map, #initialize, #join, #map, #to_ary, #to_s

Class Method Details

.chain(initial = nil, &block) ⇒ Object


5
6
7
# File 'lib/monadic/either.rb', line 5

def self.chain(initial=nil, &block)
  Either::Chain.new(&block).call(initial)
end

.unit(value) ⇒ Object


9
10
11
12
13
14
15
# File 'lib/monadic/either.rb', line 9

def self.unit(value)
  return value if value.is_a? Either
  return Nothing                  if value.is_a? Nothing
  return Success.new(value.fetch) if value.is_a? Just
  return Failure.new(value)       if value.nil? || (value.respond_to?(:empty?) && value.empty?) || !value
  return Success.new(value)
end

Instance Method Details

#bind(proc = nil, &block) ⇒ Success, Failure Also known as: >=, +

Allows privileged access to the Either's inner value from within a block. This block should return a Success or Failure itself. It will be coerced into #Either

Returns:


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

def bind(proc=nil, &block)
  return self if failure?
  return concat(proc) if proc.is_a? Either

  begin
    Either(call(proc, block))
  rescue StandardError => error
    Failure(error)
  end
end

#else(value = nil, &block) ⇒ Object

Deprecated.

46
47
48
49
50
51
# File 'lib/monadic/either.rb', line 46

def else(value=nil, &block)
  warn 'Either#else is deprecated and will be removed in a future version, use Either#or instead'
  return Failure(block.call(@value)) if failure? && block_given?
  return Failure(value) if failure?
  return self
end

#failure?Boolean

Returns:

  • (Boolean)

63
64
65
# File 'lib/monadic/either.rb', line 63

def failure?
  is_a? Failure
end

#fetch(default = @value) ⇒ Object Also known as: _


53
54
55
56
# File 'lib/monadic/either.rb', line 53

def fetch(default=@value)
  return default if failure?
  return @value
end

#or(value = nil, &block) ⇒ Success, Failure

If it is a Failure it will return a new Failure with the provided value

Returns:


39
40
41
42
43
# File 'lib/monadic/either.rb', line 39

def or(value=nil, &block)
  return Failure(block.call(@value)) if failure? && block_given?
  return Failure(value) if failure?
  return self
end

#success?Boolean

Returns:

  • (Boolean)

59
60
61
# File 'lib/monadic/either.rb', line 59

def success?
  is_a? Success
end