Class: Plumb::TaggedHash

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

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, wrap, #|

Methods included from Callable

#parse, #resolve

Constructor Details

#initialize(hash_type, key, children) ⇒ TaggedHash

Returns a new instance of TaggedHash.

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/plumb/tagged_hash.rb', line 11

def initialize(hash_type, key, children)
  @hash_type = hash_type
  @key = Key.wrap(key)
  @children = children

  raise ArgumentError, 'all types must be HashClass' if @children.size.zero? || @children.any? do |t|
    !t.is_a?(HashClass)
  end
  raise ArgumentError, "all types must define key #{@key}" unless @children.all? { |t| !!t.at_key(@key) }

  # types are assumed to have literal values for the index field :key
  @index = @children.each.with_object({}) do |t, memo|
    key_type = t.at_key(@key)
    raise ParseError, "key type at :#{@key} #{key_type} must be a Match type" unless key_type.is_a?(MatchClass)

    memo[key_type.children[0]] = t
  end

  freeze
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



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

def children
  @children
end

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

Instance Method Details

#call(result) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/plumb/tagged_hash.rb', line 32

def call(result)
  result = @hash_type.call(result)
  return result unless result.valid?

  child = @index[result.value[@key.to_sym]]
  return result.invalid(errors: "expected :#{@key.to_sym} to be one of #{@index.keys.join(', ')}") unless child

  child.call(result)
end