Created
January 28, 2013 11:30
-
-
Save maliqq/4654789 to your computer and use it in GitHub Desktop.
Mongoid::CounterCache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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