Last active
August 29, 2015 14:19
-
-
Save jakeonrails/545a97eaafebf4c341a8 to your computer and use it in GitHub Desktop.
find each by column
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActiveRecord::Base | |
def self.find_each_by(column, options={}, &block) | |
return enum_for(:find_each_by_column) unless block_given? | |
last_value = last_id = nil | |
order = options.fetch(:order, :asc) | |
batch_size = options.fetch(:batch_size, 1000) | |
operator = order == :asc ? '>=' : '<=' | |
loop do | |
relation = all | |
relation = relation.order("#{column}, id #{order}") | |
relation = relation.where("#{column} #{operator} ?", last_value) if last_value | |
relation = relation.where("id #{operator[0]} ?", last_id) if last_id | |
relation = relation.limit(batch_size) | |
results = relation.to_a | |
break if results.empty? | |
results.each(&block) | |
last_value = results.last.send(column) | |
last_id = results.last.id | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment