Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Last active May 22, 2019 17:51
Show Gist options
  • Save virtualstaticvoid/8705533 to your computer and use it in GitHub Desktop.
Save virtualstaticvoid/8705533 to your computer and use it in GitHub Desktop.

Revisions

  1. virtualstaticvoid revised this gist Jan 30, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion active_relation_extensions.rb
    Original file line number Diff line number Diff line change
    @@ -38,6 +38,6 @@ def find_in_batches_with_order(options = {})

    module ActiveRecord
    module Querying
    delegate :find_each_with_order, :find_each_with_order, :to => :scoped
    delegate :find_each_with_order, :find_in_batches_with_order, :to => :scoped
    end
    end
  2. virtualstaticvoid created this gist Jan 30, 2014.
    43 changes: 43 additions & 0 deletions active_relation_extensions.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    module ActiveRelationExtensions

    def find_each_with_order(options = {})
    find_in_batches_with_order(options) do |records|
    records.each { |record| yield record }
    end
    end

    # NOTE: any limit() on the query is overridden with the batch size
    def find_in_batches_with_order(options = {})
    options.assert_valid_keys(:batch_size)

    relation = self

    start = 0
    batch_size = options.delete(:batch_size) || 1000

    relation = relation.limit(batch_size)
    records = relation.offset(start).to_a

    while records.any?
    records_size = records.size

    yield records

    break if records_size < batch_size

    # get the next batch
    start += batch_size
    records = relation.offset(start + 1).to_a
    end

    end

    end

    ActiveRecord::Relation.send(:include, ActiveRelationExtensions)

    module ActiveRecord
    module Querying
    delegate :find_each_with_order, :find_each_with_order, :to => :scoped
    end
    end