module FancyCount::HasCountable

Public Instance Methods

fancy_counter(name, options = {}) click to toggle source
# File lib/fancy_count/has_countable.rb, line 56
def fancy_counter(name, options = {})
  counter_method_name = "fancy_#{name.to_s.singularize}_counter"
  count_method_name = "fancy_#{name.to_s.singularize}_count"
  lazily_recalculate_counter = false

  fancy_counters << {name: name, counter_name: counter_method_name, reconcile_logic: options[:reconcile_logic]}

  if options[:reconcile_on_missing] && !options[:reconcile_logic]
    raise ArgumentError.new("reconcile is required")
  end

  if options[:reconcile_on_missing] && options[:reconcile_logic]
    lazily_recalculate_counter = true
  end

  define_method counter_method_name do
    counter_key = "#{id}_#{self.class.name.underscore}_#{counter_method_name}"
    current_value = fancy_counter_value(counter_key)
    counter = ::FancyCount::Counter.new(counter_key)

    if lazily_recalculate_counter && current_value.nil?
      starting_value = send(options[:reconcile_logic])
      counter.change(starting_value)
    end

    counter
  end

  define_method count_method_name do
    public_send(counter_method_name).value
  end

  if respond_to?(:after_discard)
    after_discard do
      # Remove the key/value from Redis/adapter
      public_send(counter_method_name).delete
    end
  else
    after_destroy do
      # Remove the key/value from Redis/adapter
      public_send(counter_method_name).delete
    end
  end
end
fancy_counter_value(counter_key) click to toggle source
# File lib/fancy_count/has_countable.rb, line 102
def fancy_counter_value(counter_key)
  case FancyCount.config.adapter
  when :redis
    Redis::Objects.redis.get(counter_key)
  when :test
    FancyCount::TestAdapter.counts[counter_key]
  else
    raise "Unknown adapter: #{FancyCount.config.adapter}"
  end
end
fancy_counters() click to toggle source
# File lib/fancy_count/has_countable.rb, line 45
def fancy_counters
  @fancy_counters ||= []
end
fancy_counters_reconcile(name, scope: nil) click to toggle source

DANGER: This is a VERY naive method. It is not written to be hyper performant. Do not run this on Images, Locations, Videos, or other HUGE tables!!!!

# File lib/fancy_count/has_countable.rb, line 51
def fancy_counters_reconcile(name, scope: nil)
  scope ||= all
  scope.find_each(batch_size: 100) { |record| record.fancy_counters_reconcile(name) }
end