Class: Danom::Just

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

Overview

Useful for immediately failing when a nil pops up.

name = get_name(person) #=> nil
# ... later somewhere
name.upcase # Error!

Using a Just catches the problem at the source

name = Just(get_name(person)) # Error!

Defined Under Namespace

Classes: CannotBeNil

Instance Method Summary collapse

Methods inherited from Monad

#value, #~@

Constructor Details

#initialize(value) ⇒ Just

Returns a new instance of Just.

Raises:



17
18
19
20
# File 'lib/danom/just.rb', line 17

def initialize(value)
  raise CannotBeNil if !(Monad === value) && value == nil
  super
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) ⇒ Just

Similar to Maybe#and_then but raises an error if the value ever becomes nil.

Examples:

j = Just('hello') #=> Just
text = ~j #=> 'hello'

Failing when becomes nil

j = Just({}) #=> Just
j[:name] #=> Danom::Monad::CannotBeNil

Returns:

See Also:



44
45
46
# File 'lib/danom/just.rb', line 44

def and_then(&block)
  Just.new block.call(@value)
end

#monad_valueObject



23
24
25
26
27
# File 'lib/danom/just.rb', line 23

def monad_value
  val = super
  raise CannotBeNil if val == nil
  val
end