Class: ActiveModelCachers::ColumnValueCache

Inherits:
Object
  • Object
show all
Defined in:
lib/active_model_cachers/column_value_cache.rb,
lib/active_model_cachers/active_record/patch_rails_3.rb

Instance Method Summary collapse

Constructor Details

#initializeColumnValueCache

Returns a new instance of ColumnValueCache


3
4
5
6
# File 'lib/active_model_cachers/column_value_cache.rb', line 3

def initialize
  @cache1 = Hash.new{|h, k| h[k] = {} }
  @cache2 = Hash.new{|h, k| h[k] = {} }
end

Instance Method Details

#add(object, class_name, id, foreign_key, model) ⇒ Object


8
9
10
11
# File 'lib/active_model_cachers/column_value_cache.rb', line 8

def add(object, class_name, id, foreign_key, model)
  value = (@cache1[class_name][[id, foreign_key]] ||= get_id_from(object, id, foreign_key, model))
  return ->{ (value == :not_set ? query_value(object, class_name, id, foreign_key) : value)}
end

#clean_cacheObject


29
30
31
32
# File 'lib/active_model_cachers/column_value_cache.rb', line 29

def clean_cache
  @cache1.clear
  @cache2.clear
end

#pluck_columns(object, relation, columns) ⇒ Object


36
37
38
# File 'lib/active_model_cachers/column_value_cache.rb', line 36

def pluck_columns(_, relation, columns)
  relation.pluck(*columns)
end

#query_value(object, class_name, id, foreign_key) ⇒ Object


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/active_model_cachers/column_value_cache.rb', line 13

def query_value(object, class_name, id, foreign_key)
  cache = @cache2[class_name]
  if cache.empty?
    no_data_keys = @cache1[class_name].select{|k, v| v == :not_set }.keys
    ids = no_data_keys.map(&:first).uniq
    columns = ['id', *no_data_keys.map(&:second)].uniq
    pluck_columns(object, object.where(id: ids).limit(ids.size), columns).each do |columns_data|
      model_id = columns_data.first
      columns.each_with_index do |column, index|
        cache[[model_id, column]] = columns_data[index]
      end
    end
  end
  return cache[[id, foreign_key]]
end