Module: Philiprehberger::Maybe

Defined in:
lib/philiprehberger/maybe.rb,
lib/philiprehberger/maybe/version.rb

Defined Under Namespace

Classes: Error, None, Some

Constant Summary collapse

VERSION =
'0.3.0'

Class Method Summary collapse

Class Method Details

.all?(*maybes) ⇒ Boolean

Check if all arguments are Some

Parameters:

  • maybes (Array<Some, None>)

    the Maybe values to check

Returns:

  • (Boolean)

    true if all are Some



26
27
28
# File 'lib/philiprehberger/maybe.rb', line 26

def self.all?(*maybes)
  maybes.all?(&:some?)
end

.first_some(*maybes) ⇒ Some, None

Return the first Some from the arguments, or None if all are None

Parameters:

  • maybes (Array<Some, None>)

    the Maybe values to search

Returns:

  • (Some, None)

    the first Some, or None



34
35
36
# File 'lib/philiprehberger/maybe.rb', line 34

def self.first_some(*maybes)
  maybes.find(&:some?) || None.instance
end

.from_bool(condition, value = nil) { ... } ⇒ Some, None

Build a Maybe from a boolean gate

If condition is truthy, wraps the given value (or the block’s result if a block is provided). If condition is falsy, returns None and the block is never invoked.

Parameters:

  • condition (Object)

    truthy/falsy gate

  • value (Object) (defaults to: nil)

    value to wrap when condition is truthy and no block is given

Yields:

  • optional block producing the value when condition is truthy

Returns:

  • (Some, None)

    Some when the condition passes (and the value/block result is non-nil), None otherwise



47
48
49
50
51
# File 'lib/philiprehberger/maybe.rb', line 47

def self.from_bool(condition, value = nil, &block)
  return None.instance unless condition

  wrap(block ? block.call : value)
end

.try(*error_classes) { ... } ⇒ Some, None

Execute a block, converting raised exceptions and nil results into None

Parameters:

  • error_classes (Array<Class>)

    exception classes to catch (defaults to StandardError)

Yields:

  • the block to execute

Returns:

  • (Some, None)

    Some wrapping a non-nil result, or None if the block raises a caught exception or returns nil



58
59
60
61
62
63
# File 'lib/philiprehberger/maybe.rb', line 58

def self.try(*error_classes, &block)
  error_classes = [StandardError] if error_classes.empty?
  wrap(block.call)
rescue *error_classes
  None.instance
end

.wrap(value) ⇒ Some, None

Wrap a value in a Maybe container

Parameters:

  • value (Object)

    the value to wrap

Returns:

  • (Some, None)

    Some if value is non-nil, None otherwise



14
15
16
17
18
19
20
# File 'lib/philiprehberger/maybe.rb', line 14

def self.wrap(value)
  if value.nil?
    None.instance
  else
    Some.new(value)
  end
end