Module: Mongoid::CounterCache::ClassMethods

Defined in:
lib/mongoid_countercache/counter_cache.rb

Instance Method Summary collapse

Instance Method Details

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

Defines a counter cache on the given relation

Parameters:

  • relation_name (Class)

    The name of the parent relation on which to create the cache

  • options (Hash) (defaults to: {})

    The options hash

Options Hash (options):

  • :field_name (String, Symbol)

    The name of the field in the parent document

  • :variants (Hash)

    A hash with a variant name in key and a lambda / proc in value



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mongoid_countercache/counter_cache.rb', line 15

def counter_cache(relation_name, options = {})
  field_name = (options[:field_name] || "#{self.to_s.demodulize.underscore}_count").to_s

  options[:variants].to_a.each do |key,proc|
    variant_name = "#{field_name}_#{key.to_s.strip}"

    after_create { update_parent_counter(self.send(relation_name), variant_name, 1, proc) }
    after_destroy { update_parent_counter(self.send(relation_name), variant_name, -1, proc) }
    after_update { update_parent_counter(self.send(relation_name), variant_name, 1, proc) }

    before_update do
      attributes = self.attributes.dup
      self.changes.each do |change, vals|
        self.attributes[change] = vals.first
      end
      update_parent_counter(self.send(relation_name), variant_name, -1, proc)
      self.attributes = attributes
    end
  end
  after_create { update_parent_counter(self.send(relation_name), field_name, 1) }
  after_destroy { update_parent_counter(self.send(relation_name), field_name, -1) }
end