module FancyCount::CounterCacheable

Public Instance Methods

fancy_association_count(association, counter_name) click to toggle source
# File lib/fancy_count/counter_cacheable.rb, line 92
def fancy_association_count(association, counter_name)
  scope = association.public_send(counter_name)

  if association.respond_to?(:kept)
    scope = scope.kept
  end

  scope.count
end
fancy_counter_cache(name, options = {}) click to toggle source
# File lib/fancy_count/counter_cacheable.rb, line 34
def fancy_counter_cache(name, options = {})
  counter_method_name = "fancy_#{name.to_s.singularize}_counter"
  association_name = options[:on]

  fancy_counter_caches << {name: name, counter_name: counter_method_name, association_name: association_name}

  after_create do
    fancy_association = public_send(association_name)
    fancy_association.public_send(counter_method_name).increment
  end

  if respond_to?(:after_discard)
    after_discard do
      fancy_association = public_send(association_name)
      fancy_association.public_send(counter_method_name).decrement
    end

    after_undiscard do
      fancy_association = public_send(association_name)
      fancy_association.public_send(counter_method_name).increment
    end
  else
    after_destroy do
      fancy_association = public_send(association_name)
      fancy_association.public_send(counter_method_name).decrement
    end
  end
end
fancy_counter_cache_reconcile(name, scope: nil) click to toggle source
# File lib/fancy_count/counter_cacheable.rb, line 63
def fancy_counter_cache_reconcile(name, scope: nil)
  data = fancy_counter_caches.detect { |entry| entry[:name] == name }
  raise "Unknown counter #{name}" if data.blank?

  scope ||= all
  association_data = reflect_on_association(data[:association_name])

  if association_data.polymorphic?
    scope = scope.distinct("#{data[:association_name]}_type, #{data[:association_name]}_id")
  else
    foreign_key = association_data.foreign_key
    scope = scope.distinct(foreign_key)
  end

  scope.find_each(batch_size: 100) do |record|
    record.fancy_counter_cache_reconcile(name)
  end
end
fancy_counter_caches() click to toggle source
# File lib/fancy_count/counter_cacheable.rb, line 30
def fancy_counter_caches
  @fancy_counter_caches ||= []
end