Skip to content

Instantly share code, notes, and snippets.

@matthooks
Created November 20, 2011 02:58

Revisions

  1. Matt Hooks created this gist Nov 20, 2011.
    30 changes: 30 additions & 0 deletions gistfile1.rb
    Original 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