Skip to content

Instantly share code, notes, and snippets.

@jakeonrails
Last active August 29, 2015 14:19
Show Gist options
  • Save jakeonrails/545a97eaafebf4c341a8 to your computer and use it in GitHub Desktop.
Save jakeonrails/545a97eaafebf4c341a8 to your computer and use it in GitHub Desktop.
find each by column
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