Class: Ronad::Maybe
Class Method Summary collapse
-
.from_multiple_values(*vals) ⇒ Object
Creates a single Maybe from multiple values, shorting on the first non-nil value.
Instance Method Summary collapse
-
#and_then ⇒ Maybe
Allows for safe navigation on nil.
-
#halt ⇒ Object
“Fails” a maybe given a certain condition.
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
Instance Method Details
#and_then ⇒ Maybe
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`
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 |
#halt ⇒ Object
“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 |