Class: RecordCache::Strategy::IndexCache

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#attribute, #fetch, #invalidate

Constructor Details

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

Returns a new instance of IndexCache.



20
21
22
23
# File 'lib/record_cache/strategy/index_cache.rb', line 20

def initialize(base, attribute, record_store, options)
  super
  @cache_key_prefix << "#{attribute}="
end

Class Method Details

.parse(base, record_store, options) ⇒ Object

parse the options and return (an array of) instances of this strategy



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/record_cache/strategy/index_cache.rb', line 6

def self.parse(base, record_store, options)
  return nil unless options[:index]
  return nil unless base.table_exists?
  
  raise "Index cache '#{options[:index].inspect}' on #{base.name} is redundant as index cache queries are handled by the full table cache." if options[:full_table]
  raise ":index => #{options[:index].inspect} option cannot be used unless 'id' is present on #{base.name}" unless base.columns_hash['id']
  [options[:index]].flatten.compact.map do |attribute|
    type = base.columns_hash[attribute.to_s].try(:type)
    raise "No column found for index '#{attribute}' on #{base.name}." unless type
    raise "Incorrect type (expected integer, found #{type}) for index '#{attribute}' on #{base.name}." unless type == :integer
    IndexCache.new(base, attribute, record_store, options)
  end
end

Instance Method Details

#cacheable?(query) ⇒ Boolean

Can the cache retrieve the records based on this query?

Returns:

  • (Boolean)


26
27
28
29
# File 'lib/record_cache/strategy/index_cache.rb', line 26

def cacheable?(query)
  # allow limit of 1 for has_one
  query.where_value(@attribute) && (query.limit.nil? || (query.limit == 1 && !query.sorted?))
end

#record_change(record, action) ⇒ Object

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



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/record_cache/strategy/index_cache.rb', line 32

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