Class: Mon::Monad::Maybe

Inherits:
Mon::Monad show all
Includes:
ChainableMonad
Defined in:
lib/monads/maybe.rb

Overview

Superclass for Some and None. Can be used as follows: m = Maybe[nil] # ==> None m = Maybe[5] # ==> Some[5] m = Maybe[nil] * 7 # ==> None m = Maybe[5] * 7 # ==> Some[35] m = Maybe[call_to_fun].someOperation(3) # ==> Some[...] or None, never an error

Direct Known Subclasses

None, Some

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ChainableMonad

#_, #coerce, #respond_to?

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &fun) ⇒ Object

Override to catch None



27
28
29
# File 'lib/monads/maybe.rb', line 27

def method_missing(name, *args, &fun)
  self.bind { |o| o.send(name, *args, &fun) }
end

Class Method Details

.[](obj) ⇒ Object

Use to instantiate a Maybe monad: m = Maybe[<either nil/false or not>]



33
34
35
36
37
38
39
40
41
# File 'lib/monads/maybe.rb', line 33

def self.[](obj)
  if obj.is_a? Maybe
    obj
  elsif obj
    Some[obj]
  else
    None[]
  end
end

Instance Method Details

#orFail(msg = nil) ⇒ Object

Get the value, or throw an exception (using the optional supplied msg) if it’s empty



44
45
46
47
# File 'lib/monads/maybe.rb', line 44

def orFail(msg = nil)
  msg = "#{ self } is empty!" unless msg
  throw RuntimeError.new(msg)
end

#valid?(o) ⇒ Boolean

For Contracts, DEPRECATED

Returns:

  • (Boolean)


50
51
52
# File 'lib/monads/maybe.rb', line 50

def valid?(o)
  o.is_a? Maybe
end