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.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.each_pair_interfaceObject

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. Memoized at the class level (instances are frozen; Types isn't loaded yet when this file is).



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

def self.each_pair_interface = @each_pair_interface ||= Types::Interface[:each_pair]

Instance Method Details

#accepted_typeObject



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

def accepted_type = FilteredHashMap.each_pair_interface

#call(result) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
# File 'lib/plumb/hash_map.rb', line 102

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