Class: Mongoid::Criteria
- Inherits:
-
Object
- Object
- Mongoid::Criteria
- Defined in:
- lib/locomotive/mongoid/patches.rb
Instance Method Summary collapse
- #each_by(by, &block) ⇒ Object
- #first! ⇒ Object
-
#indexed_max(field) ⇒ Object
Optimized version of the max aggregate method.
- #to_liquid ⇒ Object
- #without_sorting ⇒ Object
Instance Method Details
#each_by(by, &block) ⇒ Object
115 116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/locomotive/mongoid/patches.rb', line 115 def each_by(by, &block) idx = total = 0 set_limit = [:limit] while ((results = ordered_clone.limit(by).skip(idx)) && results.any?) results.each do |result| return self if set_limit and set_limit >= total total += 1 yield result end idx += by end self end |
#first! ⇒ Object
102 103 104 105 106 107 108 |
# File 'lib/locomotive/mongoid/patches.rb', line 102 def first! self.first.tap do |model| if model.nil? raise Mongoid::Errors::DocumentNotFound.new(self.klass, self.selector) end end end |
#indexed_max(field) ⇒ Object
Optimized version of the max aggregate method. It works efficiently only if the field is part of a MongoDB index. more here: stackoverflow.com/questions/4762980/getting-the-highest-value-of-a-column-in-mongodb
132 133 134 135 136 137 138 139 140 |
# File 'lib/locomotive/mongoid/patches.rb', line 132 def indexed_max(field) _criteria = criteria.order_by(field.to_sym.desc).only(field.to_sym) selector = _criteria.send(:selector_with_type_selection) fields = _criteria.[:fields] sort = _criteria.[:sort] document = collection.find(selector).projection(fields).sort(sort).limit(1).first document ? document[field.to_s].to_i : nil end |
#to_liquid ⇒ Object
142 143 144 |
# File 'lib/locomotive/mongoid/patches.rb', line 142 def to_liquid Locomotive::Liquid::Drops::ProxyCollection.new(self) end |
#without_sorting ⇒ Object
110 111 112 |
# File 'lib/locomotive/mongoid/patches.rb', line 110 def without_sorting clone.tap { |crit| crit..delete(:sort) } end |