Class: Monadic::Either Abstract
Overview
This class is abstract.
Chains function calls and stops executing if one of them fails.
Defined Under Namespace
Classes: Chain
Class Method Summary collapse
Instance Method Summary collapse
-
#bind(proc = nil, &block) ⇒ Success, Failure
(also: #>=, #+)
Allows privileged access to the
Either
‘s inner value from within a block. - #else(value = nil, &block) ⇒ Object deprecated Deprecated.
- #failure? ⇒ Boolean
- #fetch(default = @value) ⇒ Object (also: #_)
-
#or(value = nil, &block) ⇒ Success, Failure
If it is a Failure it will return a new Failure with the provided value.
- #success? ⇒ Boolean
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
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 |
#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
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 |