Class: ActiveModelCachers::ColumnValueCache
- Inherits:
-
Object
- Object
- ActiveModelCachers::ColumnValueCache
- Defined in:
- lib/active_model_cachers/column_value_cache.rb,
lib/active_model_cachers/patches/patch_rails_3.rb
Instance Method Summary collapse
- #add(object, class_name, id, foreign_key, model) ⇒ Object
- #clean_cache ⇒ Object
-
#initialize ⇒ ColumnValueCache
constructor
A new instance of ColumnValueCache.
- #pluck_columns(object, relation, columns) ⇒ Object
- #query_value(object, class_name, id, foreign_key) ⇒ Object
Constructor Details
#initialize ⇒ ColumnValueCache
Returns a new instance of ColumnValueCache.
4 5 6 7 |
# File 'lib/active_model_cachers/column_value_cache.rb', line 4 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
9 10 11 12 |
# File 'lib/active_model_cachers/column_value_cache.rb', line 9 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_cache ⇒ Object
30 31 32 33 |
# File 'lib/active_model_cachers/column_value_cache.rb', line 30 def clean_cache @cache1.clear @cache2.clear end |
#pluck_columns(object, relation, columns) ⇒ Object
37 38 39 |
# File 'lib/active_model_cachers/column_value_cache.rb', line 37 def pluck_columns(_, relation, columns) relation.pluck(*columns) end |
#query_value(object, class_name, id, foreign_key) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/active_model_cachers/column_value_cache.rb', line 14 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 |