Class: RedisMemo::Batch

Inherits:
Object
  • Object
show all
Defined in:
lib/redis_memo/batch.rb

Constant Summary collapse

THREAD_KEY =
:__redis_memo_current_batch__

Class Method Summary collapse

Class Method Details

.closeObject



16
17
18
19
20
21
22
# File 'lib/redis_memo/batch.rb', line 16

def self.close
  if current
    futures = current
    Thread.current[THREAD_KEY] = nil
    futures
  end
end

.currentObject



24
25
26
# File 'lib/redis_memo/batch.rb', line 24

def self.current
  Thread.current[THREAD_KEY]
end

.executeObject



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
# File 'lib/redis_memo/batch.rb', line 28

def self.execute
  futures = close
  return unless futures

  cached_results = {}
  method_cache_keys = nil

  RedisMemo::Tracer.trace('redis_memo.cache.batch.read', nil) do
    method_cache_keys = RedisMemo::MemoizeMethod.method_cache_keys(
      futures.map(&:context),
    )

    if method_cache_keys
      cached_results = RedisMemo::Cache.read_multi(*method_cache_keys)
    end
  end

  RedisMemo::Tracer.trace('redis_memo.cache.batch.execute', nil) do
    results = Array.new(futures.size)
    futures.each_with_index do |future, i|
      future.method_cache_key = method_cache_keys ? method_cache_keys[i] : ''
      results[i] = future.execute(cached_results)
    end
    results
  end
end

.openObject



8
9
10
11
12
13
14
# File 'lib/redis_memo/batch.rb', line 8

def self.open
  if current
    raise RedisMemo::RuntimeError, 'Batch can not be nested'
  end

  Thread.current[THREAD_KEY] = []
end