Class: Searchkick::IndexCache

Inherits:
Object
  • Object
show all
Defined in:
lib/searchkick/index_cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(max_size: 20) ⇒ IndexCache

Returns a new instance of IndexCache.



3
4
5
6
7
# File 'lib/searchkick/index_cache.rb', line 3

def initialize(max_size: 20)
  @data = {}
  @mutex = Mutex.new
  @max_size = max_size
end

Instance Method Details

#clearObject



24
25
26
27
28
# File 'lib/searchkick/index_cache.rb', line 24

def clear
  @mutex.synchronize do
    @data.clear
  end
end

#fetch(name) ⇒ Object

probably a better pattern for this but keep it simple



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/searchkick/index_cache.rb', line 11

def fetch(name)
  # thread-safe in MRI without mutex
  # due to how context switching works
  @mutex.synchronize do
    if @data.key?(name)
      @data[name]
    else
      @data.clear if @data.size >= @max_size
      @data[name] = yield
    end
  end
end