Created
November 20, 2011 02:58
Revisions
-
Matt Hooks created this gist
Nov 20, 2011 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,30 @@ 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