Module: VolatileCounterCache::ClassMethods

Defined in:
lib/volatile_counter_cache/class_methods.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.

Parameters:

  • association_name (Symbol)

    Association name used to counter method, cache key, and counting.

  • cache (ActiveSupport::Cache::Store)

    A store object to store count for each key.

  • cache_options (Hash) (defaults to: {})

    Options for cache store.

  • counter_method_name (String) (defaults to: nil)

    An optional String to change counter method name.

  • foreign_key (Symbol) (defaults to: nil)

    An optional Symbol to change cache key at callback.



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

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).size
    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