Module: LoyalCore::ActiveModel::FixCounterCache::ClassMethods

Defined in:
lib/loyal_core/active_model/fix_counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#loyal_core_fix_counter_cache(*args) ⇒ Object

usage:

self.loyal_core_fix_counter_cache :folder_id => {
  :counter => :articles_count,
  :class   => ::Ruby800::Juice::Folder
}


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/loyal_core/active_model/fix_counter_cache.rb', line 19

def loyal_core_fix_counter_cache *args
  options = args.extract_options!

  options.each do |key, opts|
    before_save do |r|
      _id = key
      _counter = opts[:counter]
      _class   = opts[:class]

      if !(r.new_record?) && r.send(:"#{_id}_changed?")
        _class.decrement_counter(:"#{_counter}", r.send(:"#{_id}_was"))
        _class.increment_counter(:"#{_counter}", r.send(:"#{_id}"))
      end
    end
  end
end