Class: Plumb::HashMap

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

Defined Under Namespace

Classes: FilteredHashMap

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Composable

#>>, #[], #as_node, #build, #check, #defer, #generate, included, #invalid, #invoke, #match, #metadata, #not, #pipeline, #policy, #static, #to_json_schema, #to_s, #transform, #value, #where, #with, wrap, #|

Methods included from Callable

#parse, #resolve

Constructor Details

#initialize(key_type, value_type) ⇒ HashMap

Returns a new instance of HashMap.



11
12
13
14
15
16
# File 'lib/plumb/hash_map.rb', line 11

def initialize(key_type, value_type)
  @key_type = key_type
  @value_type = value_type
  @children = [key_type, value_type].freeze
  freeze
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



9
10
11
# File 'lib/plumb/hash_map.rb', line 9

def children
  @children
end

Instance Method Details

#call(result) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/plumb/hash_map.rb', line 18

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

  errors = {}

  parsed = result.value.each.with_object({}) do |(key, value), memo|
    key_r = @key_type.resolve(key)
    value_r = @value_type.resolve(value)
    errs = []
    errs << "key #{key_r.errors}" unless key_r.valid?
    errs << "value #{value_r.value.inspect} #{value_r.errors}" unless value_r.valid?
    errors[key] = errs unless errs.empty?
    memo[key_r.value] = value_r.value
  end

  errors.empty? ? result.valid(parsed) : result.invalid(errors:)
end

#filteredObject



36
37
38
# File 'lib/plumb/hash_map.rb', line 36

def filtered
  FilteredHashMap.new(@key_type, @value_type)
end