Class: OccamsRecord::EagerLoaders::Base

Inherits:
Object
  • Object
show all
Includes:
Builder
Defined in:
lib/occams-record/eager_loaders/base.rb

Overview

Base class for eagoer loading an association. IMPORTANT eager loaders MUST remain stateless after initialization!

Direct Known Subclasses

BelongsTo, Habtm, HasOne, Through

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Builder

#eager_load, #eager_load_many, #eager_load_one, #nest

Constructor Details

#initialize(ref, scope = nil, use: nil, as: nil, optimizer: :select) { ... } ⇒ Base

ActiveRecord::Relation on which you may call all the normal query hethods (select, where, etc) as well as any scopes you’ve defined on the model.

Parameters:

  • ref (ActiveRecord::Association)

    the ActiveRecord association

  • scope (Proc) (defaults to: nil)

    a scope to apply to the query (optional). It will be passed an

  • use (Array(Module)) (defaults to: nil)

    optional Module to include in the result class (single or array)

  • as (Symbol) (defaults to: nil)

    Load the association usign a different attribute name

  • optimizer (Symbol) (defaults to: :select)

    Only used for ‘through` associations. Options are :none (load all intermediate records) | :select (load all intermediate records but only SELECT the necessary columns)

Yields:

  • perform eager loading on this association (optional)



21
22
23
24
25
26
27
28
# File 'lib/occams-record/eager_loaders/base.rb', line 21

def initialize(ref, scope = nil, use: nil, as: nil, optimizer: :select, &builder)
  @ref, @scope, @use, @as = ref, scope, use, as
  @model = ref.klass
  @name = (as || ref.name).to_s
  @eager_loaders = EagerLoaders::Context.new(@model)
  @optimizer = optimizer
  instance_exec(&builder) if builder
end

Instance Attribute Details

#nameString (readonly)

Returns association name.

Returns:

  • (String)

    association name



10
11
12
# File 'lib/occams-record/eager_loaders/base.rb', line 10

def name
  @name
end

Instance Method Details

#run(rows, query_logger: nil, measurements: nil) ⇒ Object

Run the query and merge the results into the given rows.

Parameters:

  • rows (Array<OccamsRecord::Results::Row>)

    Array of rows used to calculate the query.

  • query_logger (Array<String>) (defaults to: nil)


36
37
38
39
40
41
42
# File 'lib/occams-record/eager_loaders/base.rb', line 36

def run(rows, query_logger: nil, measurements: nil)
  query(rows) { |*args|
    assoc_rows = args[0] ? Query.new(args[0], use: @use, eager_loaders: @eager_loaders, query_logger: query_logger, measurements: measurements).run : []
    merge! assoc_rows, rows, *args[1..-1]
  }
  nil
end