Module: VolatileCounterCache::ClassMethods

Defined in:
lib/volatile_counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#volatile_counter_cache(association_name, cache:, cache_options: {}, counter_method_name: nil, foreign_key: nil) ⇒ Object

Define counter method and callback using given cache store for 1:N association.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/volatile_counter_cache.rb', line 27

def volatile_counter_cache(association_name, cache:, cache_options: {}, counter_method_name: nil, foreign_key: nil)
  counter_method_name = counter_method_name || "#{association_name}_count"
  cache_key_prefix = "#{CACHE_KEY_PREFIX}/#{model_name}/#{association_name}"

  define_method(counter_method_name) do
    cache.fetch("#{cache_key_prefix}/#{id}", cache_options) do
      send(association_name).count
    end
  end

  foreign_key = foreign_key || "#{table_name.singularize }_id"
  child_class = association_name.to_s.singularize.camelize.constantize
  callback_proc = -> do
    cache.delete("#{cache_key_prefix}/#{send(foreign_key)}", cache_options)
  end
  child_class.after_create(&callback_proc)
  child_class.after_destroy(&callback_proc)
end