Class: Danom::Default

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

Overview

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

Instance Method Summary collapse

Methods inherited from Monad

#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/danom/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 Danom::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 #=> Danom::Default
name = ~d # 'Missing name'

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

Combining with a Maybe

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

See Also:

  • Monad#method_missing


41
42
43
44
45
46
47
# File 'lib/danom/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/danom/default.rb', line 15

def monad_value
  super || @fallback
end