Module: Pipeloader::Batch::Model

Extended by:
ActiveSupport::Concern
Defined in:
lib/pipeloader/batch/model.rb

Overview

Include into an ActiveRecord model to enable batch-loaded relationships.

class Author < ApplicationRecord
  include Pipeloader::Batch::Model
  batch_has_many   :books            # chainable, batched (where/order/limit)
  batch_has_one    :profile
  batch_belongs_to :publisher
  batch_count      :books_count
  batch_aggregate  :total_pages, of: :books, function: :sum, column: :pages
end

‘batch_has_many` returns a BatchProxy: a lazy, chainable relation-like object whose load is batched across every live instance of the class in the current Context — and whose .where/.order/.limit are applied INSIDE that one batched query (limit/offset per group). belongs_to/has_one return a single native record, batched via the load interceptor. Aggregates return batched scalars.

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#_fetcher_state(name) ⇒ Object



154
155
156
157
158
159
160
161
162
# File 'lib/pipeloader/batch/model.rb', line 154

def _fetcher_state(name)
  ivar = :"@_pipeloader_batch_state_#{name}"
  return instance_variable_get(ivar) if instance_variable_defined?(ivar)

  fetcher = self.class._pipeloader_batch_fetchers[name]
  raise Pipeloader::Batch::Error, "no batch relationship named #{name.inspect}" unless fetcher

  instance_variable_set(ivar, Pipeloader::Batch::FetcherState.new(fetcher))
end

#_pipeloader_batch_contextObject

This record’s sibling group: the records loaded with it (stamped at load time by Pipeloader::Batch::LoadGrouping), or a solo group when it was loaded or built on its own. Every batch method reads its siblings from here.



144
145
146
# File 'lib/pipeloader/batch/model.rb', line 144

def _pipeloader_batch_context
  @_pipeloader_batch_context ||= Pipeloader::Batch::Context.new.tap { |c| c.add(self) }
end

#_pipeloader_batch_scope_cacheObject

Per-instance cache for batched collection scopes, keyed by [name, scope].



165
166
167
# File 'lib/pipeloader/batch/model.rb', line 165

def _pipeloader_batch_scope_cache
  @_pipeloader_batch_scope_cache ||= {}
end

#batch_load(name) ⇒ Object

Aggregate readers route through here; record associations use BatchProxy (has_many) or AR’s own reader (belongs_to/has_one).



150
151
152
# File 'lib/pipeloader/batch/model.rb', line 150

def batch_load(name)
  _fetcher_state(name).fetch(self)
end