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


316
317
318
319
320
321
322
323
324
325
326
# File 'lib/dry/monads/maybe.rb', line 316

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 }


339
340
341
342
343
# File 'lib/dry/monads/maybe.rb', line 339

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