module Dry::Monads::Maybe::Hash

Utilities for working with hashes storing Maybe values

Public Class Methods

all(hash, trace = RightBiased::Left.trace_caller) click to toggle source

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

@example

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()

@param hash [::Hash<Object,Maybe>] @return [Maybe<::Hash>]

# 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) click to toggle source

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

@example

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 }

@param hash [::Hash<Object,Maybe>] @return [::Hash]

# 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