File: executor_proxy.rb

package info (click to toggle)
ruby-batch-loader 2.0.5%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 284 kB
  • sloc: ruby: 783; makefile: 6; sh: 4
file content (58 lines) | stat: -rw-r--r-- 1,138 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
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
51
52
53
54
55
56
57
58
# frozen_string_literal: true

require_relative "./executor"

class BatchLoader
  class ExecutorProxy
    attr_reader :default_value, :block, :global_executor

    def initialize(default_value, key, &block)
      @default_value = default_value
      @block = block
      @block_hash_key = [block.source_location, key]
      @global_executor = BatchLoader::Executor.ensure_current
    end

    def add(item:)
      items_to_load << item
    end

    def list_items
      items_to_load.to_a.freeze
    end

    def delete(items:)
      global_executor.items_by_block[@block_hash_key] = items_to_load - items
    end

    def load(item:, value:)
      loaded[item] = value
    end

    def loaded_value(item:)
      if value_loaded?(item: item)
        loaded[item]
      else
        @default_value.dup
      end
    end

    def value_loaded?(item:)
      loaded.key?(item)
    end

    def unload_value(item:)
      loaded.delete(item)
    end

    private

    def items_to_load
      global_executor.items_by_block[@block_hash_key]
    end

    def loaded
      global_executor.loaded_values_by_block[@block_hash_key]
    end
  end
end