Class: Kumi::Core::Compiler::Accessors::MaterializeAccessor

Inherits:
Object
  • Object
show all
Extended by:
Base
Defined in:
lib/kumi/core/compiler/accessors/materialize_accessor.rb

Constant Summary

Constants included from Base

Base::MISSING

Class Method Summary collapse

Methods included from Base

assert_array!, assert_hash!, fetch_key, missing_array_action, missing_key_action, next_enters_array?, warn_mismatch

Class Method Details

.build(operations, path_key, policy, key_policy) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/kumi/core/compiler/accessors/materialize_accessor.rb', line 10

def self.build(operations, path_key, policy, key_policy)
  mode = :materialize
  lambda do |data|
    walk = nil
    walk = lambda do |node, pc|
      return node if pc >= operations.length

      op = operations[pc]
      case op[:type]
      when :enter_hash
        assert_hash!(node, path_key, mode)
        preview_array = next_enters_array?(operations, pc)
        policy_for = preview_array ? :indifferent : key_policy
        next_node = fetch_key(node, op[:key], policy_for)
        if next_node == Base::MISSING
          case missing_key_action(policy)
          when :yield_nil then return nil
          when :skip      then return preview_array ? [] : nil
          when :raise     then raise KeyError, "Missing key '#{op[:key]}' at '#{path_key}' (#{mode})"
          end
        end
        walk.call(next_node, pc + 1)

      when :enter_array
        if node.nil?
          case missing_array_action(policy)
          when :yield_nil then return nil
          when :skip      then return []
          when :raise     then raise KeyError, "Missing array at '#{path_key}' (#{mode})"
          end
        end
        assert_array!(node, path_key, mode)
        node.map { |child| walk.call(child, pc + 1) }

      else
        raise "Unknown operation: #{op.inspect}"
      end
    end
    walk.call(data, 0)
  end
end