Class: Ronad::Maybe

Inherits:
Monad
  • Object
show all
Defined in:
lib/ronad/maybe.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Monad

#continue, #initialize, #monad_value, #value, #~@

Constructor Details

This class inherits a constructor from Ronad::Monad

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Ronad::Monad

Class Method Details

.from_multiple_values(*vals) ⇒ Object

Creates a single Maybe from multiple values, shorting on the first non-nil value.



7
8
9
# File 'lib/ronad/maybe.rb', line 7

def self.from_multiple_values(*vals)
  new vals.detect { |v| Monad.new(v).value != nil }
end

Instance Method Details

#and_thenMaybe

Allows for safe navigation on nil.

nil&.m1&.m2&.m3 #=> nil

~Maybe(nil).m1.m2.m3 #=> nil

Using a Maybe really shines when accessing a hash

~Maybe({})[:person][:name].downcase.split(' ').join('-') #=> nil

{}.dig(:person, :name)&.downcase.&split(' ')&.join('-') #=> nil

Using #and_then without the Monad#method_missing sugar is also useful if you need to pass your value to another method

Maybe(nil).and_then{ |value| JSON.parse(value) } #=> Maybe

The block only gets executed if value is not ‘nil`

Returns:

See Also:

  • Ronad::Monad#method_missing


32
33
34
35
36
37
38
# File 'lib/ronad/maybe.rb', line 32

def and_then
  if @value
    Maybe.new yield(@value)
  else
    Maybe.new(nil)
  end
end

#haltObject

“Fails” a maybe given a certain condition. If the condition is ‘true` then Maybe(nil) will be returned.



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

def halt
  and_then do |value|
    value unless yield value
  end
end