Module: Gricer::Mongoid::CounterCache::ClassMethods

Defined in:
lib/gricer/mongoid/counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#counter_cache(options = {}) ⇒ Object



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

def counter_cache(options = {})
  return if options[:counter_cache].blank?
  
  counter_field = if options[:counter_cache].to_s != 'true'
    options[:counter_cache].to_s
  else 
    "#{options.inverse_of? ? options.inverse_of : self.name.gsub(/(.*::)/, '').downcase.pluralize }_count" 
  end

  set_callback(:create, :after) do |document|
    current_document = document
    if relation = document.send(options.name)
      relation.inc(counter_field, 1)
    end
  end

  set_callback(:destroy, :after) do |document|
    current_document = document
    if relation = document.send(options.name) && relation && relation.class.fields.keys.include?(counter_field)
      relation.inc(counter_field, -1)
    end
  end
end

#referenced_in(name, options = {}, &block) ⇒ Object Also known as: belongs_to_related, belongs_to



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/gricer/mongoid/counter_cache.rb', line 38

def referenced_in(name, options = {}, &block)
  counter_cache = options.delete :counter_cache
  
  characterize(name, ::Mongoid::Relations::Referenced::In, options, &block).tap do |meta|
    relate(name, meta)
    reference(meta)
    autosave(meta)
    counter_cache(meta.merge counter_cache: counter_cache)
    validates_relation(meta)
  end
end