Class: RecordCache::Strategy::IndexCache

Inherits:
Base
  • Object
show all
Defined in:
lib/record_cache/strategy/index_cache.rb

Constant Summary

Constants inherited from Base

Base::ATTRIBUTES_KEY, Base::CLASS_KEY

Instance Method Summary collapse

Methods inherited from Base

#fetch

Constructor Details

#initialize(base, strategy_id, record_store, options) ⇒ IndexCache

Returns a new instance of IndexCache.



5
6
7
8
9
10
11
12
13
# File 'lib/record_cache/strategy/index_cache.rb', line 5

def initialize(base, strategy_id, record_store, options)
  super
  @index = options[:index]
  # check the index
  type = @base.columns_hash[@index.to_s].try(:type)
  raise "No column found for index '#{@index}' on #{@base.name}." unless type
  raise "Incorrect type (expected integer, found #{type}) for index '#{@index}' on #{@base.name}." unless type == :integer
  @index_cache_key_prefix = cache_key(@index) # "/rc/<model>/<index>"
end

Instance Method Details

#cacheable?(query) ⇒ Boolean

Can the cache retrieve the records based on this query?

Returns:

  • (Boolean)


16
17
18
# File 'lib/record_cache/strategy/index_cache.rb', line 16

def cacheable?(query)
  query.where_id(@index) && query.limit.nil?
end

#invalidate(value) ⇒ Object

Explicitly invalidate the record cache for the given value



35
36
37
# File 'lib/record_cache/strategy/index_cache.rb', line 35

def invalidate(value)
  version_store.increment(index_cache_key(value))
end

#record_change(record, action) ⇒ Object

Handle create/update/destroy (use record.previous_changes to find the old values in case of an update)



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/record_cache/strategy/index_cache.rb', line 21

def record_change(record, action)
  if action == :destroy
    remove_from_index(record.send(@index), record.id)
  elsif action == :create
    add_to_index(record.send(@index), record.id)
  else
    index_change = record.previous_changes[@index.to_s]
    return unless index_change
    remove_from_index(index_change[0], record.id)
    add_to_index(index_change[1], record.id)
  end
end