Module: ActiveTools::ActiveRecord::CustomCounterCache::ClassMethods

Defined in:
lib/active_tools/active_record/custom_counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#custom_counter_cache_for(*args) ⇒ Object



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
41
42
# File 'lib/active_tools/active_record/custom_counter_cache.rb', line 12

def custom_counter_cache_for(*args)
  mapping = args.extract_options!
  mapping.each do |assoc_name, value|
    assoc_name = assoc_name.to_s
    if assoc_name.last == "*"
      if value.is_a?(Hash)
        assoc_mapping = value.merge(assoc_name => value)
      end
      assoc_name = assoc_name[0..-2]
    else
      assoc_mapping = value
    end
    reflection = reflections[assoc_name.to_sym]
  
    unless method_defined? :custom_counter_cache_after_create
      include ActiveRecord::CustomCounterCache::InstanceMethods
    end
  
    after_create lambda { |record|
      record.custom_counter_cache_after_create(assoc_name, reflection, assoc_mapping)
    }

    before_destroy lambda { |record|
      record.custom_counter_cache_before_destroy(assoc_name, reflection, assoc_mapping)
    }

    after_update lambda { |record|
      record.custom_counter_cache_after_update(assoc_name, reflection, assoc_mapping)
    }
  end
end