Created
November 20, 2011 02:58
-
-
Save matthooks/1379747 to your computer and use it in GitHub Desktop.
Simple counter cache setup for MongoMapper that supports single collection inheritance.
This file contains 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 CounterCache | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def counter_cache(field) | |
class_eval <<-EOF | |
after_create "increment_counter_for_#{field}" | |
after_destroy "decrement_counter_for_#{field}" | |
EOF | |
end | |
end | |
module InstanceMethods | |
def method_missing(method, *args) | |
if matches = method.to_s.match(/^(in|de)crement_counter_for_(.*)$/) then | |
dir = matches[1] == "in" ? 1 : -1 | |
parent_association = matches[2] | |
if parent = self.send(parent_association) then | |
name = "#{self.class.collection_name}_count" | |
if parent.respond_to?(name) | |
parent.increment(name => dir) | |
end | |
end | |
else | |
super | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment