Skip to content

Instantly share code, notes, and snippets.

@maliqq
Created January 28, 2013 11:30
Show Gist options
  • Save maliqq/4654789 to your computer and use it in GitHub Desktop.
Save maliqq/4654789 to your computer and use it in GitHub Desktop.
Mongoid::CounterCache
module Mongoid
module CounterCache
extend ActiveSupport::Concern
included do
end
module ClassMethods
def counter_cache(name, counter_field = nil)
counter_field ||= "#{self.name.underscore.pluralize}_counter"
# -- field --
reflection = self.reflect_on_association(name)
reflection.klass.field counter_field, type: Integer, default: 0
# -- callbacks --
after_create "increment_#{counter_field}"
after_destroy "decrement_#{counter_field}"
# -- method definitions --
define_method "increment_#{counter_field}" do
relation = send(name)
relation.inc(counter_field, 1)
end
define_method "decrement_#{counter_field}" do
relation = send(name)
relation.inc(counter_field, -1)
end
define_method "recount_#{counter_field}" do
relation = send(name)
relation.set(counter_field, self.where(relation.foreign_key => relation._id).count)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment