Module: Dry::Monads::Maybe::Hash

Defined in:
lib/dry/monads/maybe.rb

Overview

Utilities for working with hashes storing Maybe values

Class Method Summary collapse

Class Method Details

.all(hash, trace = RightBiased::Left.trace_caller) ⇒ Maybe<::Hash>

Traverses a hash with maybe values. If any value is None then None is returned

Examples:

Maybe::Hash.all(foo: Some(1), bar: Some(2)) # => Some(foo: 1, bar: 2)
Maybe::Hash.all(foo: Some(1), bar: None())  # => None()
Maybe::Hash.all(foo: None(), bar: Some(2))  # => None()

Parameters:

  • hash (::Hash<Object,Maybe>)

Returns:



345
346
347
348
349
350
351
352
353
354
355
# File 'lib/dry/monads/maybe.rb', line 345

def self.all(hash, trace = RightBiased::Left.trace_caller)
  result = hash.each_with_object({}) do |(key, value), output|
    if value.some?
      output[key] = value.value!
    else
      return None.new(trace)
    end
  end

  Some.new(result)
end

.filter(hash) ⇒ ::Hash

Traverses a hash with maybe values. Some values are unwrapped, keys with None values are removed

Examples:

Maybe::Hash.filter(foo: Some(1), bar: Some(2)) # => { foo: 1, bar: 2 }
Maybe::Hash.filter(foo: Some(1), bar: None())  # => { foo: 1 }
Maybe::Hash.filter(foo: None(), bar: Some(2))  # => { bar: 2 }

Parameters:

  • hash (::Hash<Object,Maybe>)

Returns:

  • (::Hash)


368
369
370
371
372
# File 'lib/dry/monads/maybe.rb', line 368

def self.filter(hash)
  hash.each_with_object({}) do |(key, value), output|
    output[key] = value.value! if value.some?
  end
end