Class: OccamsRecord::Batches::OffsetLimit::Scoped

Inherits:
Object
  • Object
show all
Defined in:
lib/occams-record/batches/offset_limit/scoped.rb

Overview

Implements batched loading for ActiveRecord model scopes.

Instance Method Summary collapse

Constructor Details

#initialize(model, scope, use: nil, query_logger: nil, eager_loaders: nil) ⇒ Scoped

Returns a new instance of Scoped.



8
9
10
11
# File 'lib/occams-record/batches/offset_limit/scoped.rb', line 8

def initialize(model, scope, use: nil, query_logger: nil, eager_loaders: nil)
  @model, @scope = model, scope
  @use, @query_logger, @eager_loaders = use, query_logger, eager_loaders
end

Instance Method Details

#enum(batch_size:, use_transaction: true, append_order_by: nil) ⇒ Enumerator

Returns an Enumerator that yields batches of records, of size “of”. NOTE ActiveRecord 5+ provides the ‘in_batches’ method to do something similiar, but unlike this it doesn’t respect ORDER BY.

Parameters:

  • batch_size (Integer)

    batch size

  • use_transaction (Boolean) (defaults to: true)

    Ensure it runs inside of a database transaction

  • append_order_by (String) (defaults to: nil)

    Append this column to ORDER BY to ensure consistent results. Defaults to the primary key. Pass false to disable.

Returns:

  • (Enumerator)

    yields batches



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/occams-record/batches/offset_limit/scoped.rb', line 23

def enum(batch_size:, use_transaction: true, append_order_by: nil)
  append_order =
    case append_order_by
    when false then nil
    when nil then @model.primary_key
    else append_order_by
    end

  Enumerator.new do |y|
    if use_transaction and @model.connection.open_transactions == 0
      @model.connection.transaction {
        run_batches y, batch_size, append_order
      }
    else
      run_batches y, batch_size, append_order
    end
  end
end