Class: Plumb::HashMap::FilteredHashMap

Inherits:
HashMap
  • Object
show all
Defined in:
lib/plumb/hash_map.rb

Overview

Same key/value types as a HashMap (so it inherits #initialize, #children and the hash-family #subtype_of?), but filters out invalid entries instead of rejecting the whole Hash.

Instance Method Summary collapse

Instance Method Details

#accepted_typeObject

A filtered map is lenient: it accepts ANY hash and drops non-matching entries (it never rejects a Hash), so as a #>> consumer it accepts any hash-like value — not itself. Without this, Hash >> Hash[K, V].filtered would be flagged as an illegal narrowing.



96
# File 'lib/plumb/hash_map.rb', line 96

def accepted_type = Types::EachPair

#call(result) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
# File 'lib/plumb/hash_map.rb', line 98

def call(result)
  result.invalid(errors: 'must be a Hash') unless result.value.is_a?(::Hash)

  hash = result.value.each.with_object({}) do |(key, value), memo|
    key_r = @key_type.resolve(key)
    value_r = @value_type.resolve(value)
    memo[key_r.value] = value_r.value if key_r.valid? && value_r.valid?
  end

  result.valid!(hash)
end

#node_nameObject

Naming derives #node_name when Composable is included (on HashMap), so the subclass would otherwise inherit :hash_map. Restore its own name so visitors still dispatch to their :filtered_hash_map handlers.



86
# File 'lib/plumb/hash_map.rb', line 86

def node_name = :filtered_hash_map

#value_preserving?Boolean

A filtered map DROPS non-matching entries, so it changes the value regardless of its key/value types — never value-preserving.

Returns:

  • (Boolean)


90
# File 'lib/plumb/hash_map.rb', line 90

def value_preserving? = false