Class: Danom::Maybe
Instance Method Summary collapse
-
#and_then ⇒ Maybe
Allows for safe navigation on nil.
-
#continue ⇒ Monad
“Fails” a maybe given a certain condition.
Methods inherited from Monad
#initialize, #monad_value, #value, #~@
Constructor Details
This class inherits a constructor from Danom::Monad
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class Danom::Monad
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`
26 27 28 29 30 31 32 |
# File 'lib/danom/maybe.rb', line 26 def and_then if @value Maybe.new yield(@value) else Maybe.new(nil) end end |
#continue ⇒ Monad
“Fails” a maybe given a certain condition. If the condition is ‘false` then Maybe(nil) will be returned. Useful for performing side-effects given a certain condition
Maybe([]).and_then do |value|
value.each(&:some_operation)
OtherModule.finalize! # Side Effect should only happen if there
end # are any values
The following ‘and_then` only executes if `value` responds truthy to any?
Maybe([]).continue(&:any?).and_then do |value|
value.each(&:some_operation)
OtherModule.finalize!
end
50 51 52 53 54 |
# File 'lib/danom/maybe.rb', line 50 def continue and_then do |value| value if yield value end end |