Module: FixUpdateCounters

Defined in:
app/models/ecm/downloads/download.rb

Instance Method Summary collapse

Instance Method Details

#fix_updated_countersObject



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/models/ecm/downloads/download.rb', line 2

def fix_updated_counters
  self.changes.each {|key, value|
    # key should match /master_files_id/ or /bibls_id/
    # value should be an array ['old value', 'new value']
    if key =~ /_id/
      changed_class = key.sub(/_id/, '')

      # Get real class of changed attribute, so work both with namespaced/normal models
      klass = self.association(changed_class.to_sym).klass
     
      # Try to get counter cache from association options
      begin 
         counter_name = self.association(changed_class.to_sym).options[:counter_cache]
      rescue 
        # Namespaced model return a slash, split it.
        unless (counter_name = "#{self.class.name.underscore.pluralize.split("/")[1]}_count".to_sym)
          counter_name = "#{self.class.name.underscore.pluralize}_count".to_sym
        end
      end   


      klass.decrement_counter(counter_name, value[0]) unless value[0] == nil
      klass.increment_counter(counter_name, value[1]) unless value[1] == nil
    end
  }
end