Module: Gricer::Mongoid::CounterCache::ClassMethods
- Defined in:
- lib/gricer/mongoid/counter_cache.rb
Instance Method Summary collapse
- #counter_cache(options = {}) ⇒ Object
- #referenced_in(name, options = {}, &block) ⇒ Object (also: #belongs_to_related, #belongs_to)
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( = {}) return if [:counter_cache].blank? counter_field = if [:counter_cache].to_s != 'true' [:counter_cache].to_s else "#{.inverse_of? ? .inverse_of : self.name.gsub(/(.*::)/, '').downcase.pluralize }_count" end set_callback(:create, :after) do |document| current_document = document if relation = document.send(.name) relation.inc(counter_field, 1) end end set_callback(:destroy, :after) do |document| current_document = document if relation = document.send(.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 ,
38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/gricer/mongoid/counter_cache.rb', line 38 def referenced_in(name, = {}, &block) counter_cache = .delete :counter_cache characterize(name, ::Mongoid::Relations::Referenced::In, , &block).tap do || relate(name, ) reference() autosave() counter_cache(.merge counter_cache: counter_cache) validates_relation() end end |