Module: Mongoid::MagicCounterCache::ClassMethods

Defined in:
lib/mongoid/magic_counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#counter_cache(*args, &block) ⇒ Object Also known as: magic_counter_cache


67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/mongoid/magic_counter_cache.rb', line 67

def counter_cache(*args, &block)
  options       = args.extract_options!
  name          = options[:class] || args.first.to_s
  counter_name  = get_counter_name(options)
  condition     = options[:if]
  update_condition = options[:if_update]

  increment_proc = ->(doc, inc) do
    if doc.embedded?
      parent = doc._parent
      if parent.respond_to?(counter_name)
        increment_association(parent, counter_name.to_sym, inc)
      end
    else
      relation = doc.send(name)
      if relation && relation.class.fields.keys.include?(counter_name)
        increment_association(relation, counter_name.to_sym, inc)
      end
    end
  end

  callback_proc = ->(doc, inc) do
    result = condition_result(condition, doc)
    return unless result
    increment_proc.call(doc, inc)
  end

  update_callback_proc = ->(doc) do
    return if condition.nil? || update_condition.nil? # Don't execute if there is no update condition.
    return unless update_condition.call(doc) # Determine whether to execute update increment/decrements.
    inc = condition.call(doc) ? 1 : -1
    increment_proc.call(doc, inc)
  end

  after_create( ->(doc) { callback_proc.call(doc,  1) })
  after_destroy(->(doc) { callback_proc.call(doc, -1) })
  after_update( ->(doc) { update_callback_proc.call(doc) })

end