Skip to content

Instantly share code, notes, and snippets.

@matthooks
Created November 20, 2011 02:58
Show Gist options
  • Save matthooks/1379747 to your computer and use it in GitHub Desktop.
Save matthooks/1379747 to your computer and use it in GitHub Desktop.
Simple counter cache setup for MongoMapper that supports single collection inheritance.
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