I just hate things that fail silently, just like User.order_by(:created_at).find_each
Which will simply ignore the order option….
So here comes the alternative…
class ActiveRecord::Base
# normal find_each does not use given order but uses id asc
def self.find_each_with_order(options={})
raise "offset is not yet supported" if options[:offset]
page = 1
limit = options[:limit] || 1000
loop do
offset = (page-1) * limit
batch = find(:all, options.merge(:limit => limit, :offset => offset))
page += 1
batch.each{|x| yield x }
break if batch.size < limit
end
end
end
(the 😮 is : and o)
It’s worth noting that the efficiencies gained by find_each for batch processing of large amounts of records are now lost. Also, WP is inserting a smiley in your code 😉
I think the benefits are now limited, but still better then doing a .all 😉