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

#monad_value, #to_s, #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 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:



37
38
39
# File 'lib/danom/just.rb', line 37

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