Module: ActiveRecord::OnDemand::Reading::ClassMethods

Defined in:
lib/ar-ondemand/for_reading.rb

Instance Method Summary collapse

Instance Method Details

#for_reading(options = {}) ⇒ Object

Ripped from the find_in_batches function, but customized to return an ::ActiveRecord::OnDemand::ResultSet



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ar-ondemand/for_reading.rb', line 16

def for_reading(options = {})
  if options.empty?
    res = query_for_reading self, readonly: true
    if block_given?
      yield res
      return
    end
    return res
  end

  relation = self

  unless self.arel.orders.blank? && self.arel.taken.blank?
    ::ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
  end

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

  relation = relation.reorder(batch_order_for_reading).limit(batch_size)
  records = query_for_reading(start ? relation.where(table[primary_key].gteq(start)) : relation, readonly: true)

  while records.any?
    records_size = records.size
    primary_key_offset = records.last.id

    yield records

    break if records_size < batch_size

    if primary_key_offset
      records = query_for_reading relation.where(table[primary_key].gt(primary_key_offset)), readonly: true
    else
      raise 'Primary key not included in the custom select clause'
    end
  end
end

#raw_resultsObject



11
12
13
# File 'lib/ar-ondemand/for_reading.rb', line 11

def raw_results
  query_for_reading self, readonly: true, raw: true
end