Module: MongoMapper::Plugins::BelongsToWithCounterCache::ClassMethods

Defined in:
lib/mongo_mapper_ext/plugins/belongs_to_with_counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(association_id, options = {}, &extension) ⇒ Object

CounterCache belongs_to :item, counter_cashe: true



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mongo_mapper_ext/plugins/belongs_to_with_counter_cache.rb', line 11

def belongs_to association_id, options={}, &extension          
  options.must_not.include :counter_cashe
  if options.delete(:counter_cache) || options.delete('counter_cache')
    association_id = association_id.to_s
    association_key = "#{association_id}_id"
    cache_attribute = "#{self.alias.pluralize.underscore}_count"
    cache_class = if class_name = options[:class_name]
      class_name.constantize
    else
      association_id.classify.constantize
    end
    cache_class.keys.must.include cache_attribute            
    increase_method_name = "increase_#{cache_class.alias.underscore}_#{self.alias.pluralize.underscore}_counter"
    decrease_method_name = "decrease_#{cache_class.alias.underscore}_#{self.alias.pluralize.underscore}_counter"

    define_method increase_method_name do
      cache_class.upsert!({id: self.send(association_key)}, :$inc => {cache_attribute => 1})
    end
    protected increase_method_name            

    define_method decrease_method_name do
      cache_class.upsert!({id: self.send(association_key)}, :$inc => {cache_attribute => -1})
    end
    protected decrease_method_name

    after_create increase_method_name
    after_destroy decrease_method_name
  end
  super association_id, options, &extension
end