Module: MongoMapper::Plugins::CounterCache::ClassMethods

Defined in:
lib/mongo_mapper/plugins/counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#counter_cache(association_name, options = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/mongo_mapper/plugins/counter_cache.rb', line 39

def counter_cache(association_name, options = {})
  options.symbolize_keys!

  field = options[:field] ?
    options[:field] :
    "#{self.collection_name.gsub(/.*\./, '')}_count"

  association = associations[association_name]

  if !association
    raise InvalidCounterCacheError, "You must define an association with name `#{association_name}' on model #{self}"
  end

  association_class = association.klass
  key_names = association_class.keys.keys

  if !key_names.include?(field.to_s)
    raise InvalidCounterCacheError, "Missing `key #{field.to_sym.inspect}, Integer, :default => 0' on model #{association_class}"
  end

  after_create do
    if obj = self.send(association_name)
      obj.increment(field => 1)
      obj.write_attribute(field, obj.read_attribute(field) + 1)
    end
    true
  end

  after_destroy do
    if obj = self.send(association_name)
      obj.decrement(field => 1)
      obj.write_attribute(field, obj.read_attribute(field) - 1)
    end
    true
  end
end