Class: Ronad::Default

Inherits:
Monad
  • Object
show all
Defined in:
lib/ronad/default.rb

Overview

A default “monad”. Not technically a monad as it take two values.

Instance Method Summary collapse

Methods inherited from Monad

#continue, #value, #~@

Constructor Details

#initialize(fallback, value) ⇒ Default

Returns a new instance of Default.

Parameters:

  • fallback (Object)

    The value on which to fallback if the doesn’t satisfy Just(value)

  • value (Object)


9
10
11
12
# File 'lib/ronad/default.rb', line 9

def initialize(fallback, value)
  @fallback = Just.new(fallback).value
  super(value)
end

Dynamic Method Handling

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

Instance Method Details

#and_then(&block) ⇒ Object

Note:

The fallback does not get the transformations

Allows chaining on nil values with a fallback

Default can be combined with a maybe. Extracting the value is recursive and will never return another monad.

Examples:

d = Default('Missing name', nil)
d = d.upcase.split.join #=> Ronad::Default
name = ~d # 'Missing name'

d = Default('Missing name', 'Uri')
d = d.upcase #=> Ronad::Default
name = ~d # 'URI'

Combining with a Maybe

m = Maybe(nil)
d = Default('No name', m) #=> Ronad::Default
name = ~d #=>  'No name'

See Also:

  • Monad#method_missing


41
42
43
44
45
46
47
# File 'lib/ronad/default.rb', line 41

def and_then &block
  if @value == nil
    Default.new @fallback, nil
  else
    Default.new @fallback, block.call(@value)
  end
end

#monad_valueObject



15
16
17
# File 'lib/ronad/default.rb', line 15

def monad_value
  super || @fallback
end