Class: OccamsRecord::EagerLoaders::AdHocBase

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

Overview

Base class for eager loading ad hoc associations.

Direct Known Subclasses

AdHocMany, AdHocOne

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Builder

#eager_load, #eager_load_many, #eager_load_one, #nest

Constructor Details

#initialize(name, mapping, sql, binds: {}, model: nil, use: nil) { ... } ⇒ AdHocBase

Initialize a new add hoc association.

Parameters:

  • name (Symbol)

    name of attribute to load records into

  • mapping (Hash)

    a one element Hash with the key being the local/child id and the value being the foreign/parent id

  • sql (String)

    the SQL to query the associated records. Include a bind params called ‘%ids’ for the foreign/parent ids.

  • binds (Hash) (defaults to: {})

    any additional binds for your query.

  • model (ActiveRecord::Base) (defaults to: nil)

    optional - ActiveRecord model that represents what you’re loading. required when using Sqlite.

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

    optional - Ruby modules to include in the result objects (single or array)

Yields:

  • eager load associations nested under this one

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
30
31
# File 'lib/occams-record/eager_loaders/ad_hoc_base.rb', line 23

def initialize(name, mapping, sql, binds: {}, model: nil, use: nil, &builder)
  @name = name.to_s
  @sql, @binds, @use, @model = sql, binds, use, model
  raise ArgumentError, "Add-hoc eager loading mapping must contain exactly one key-value pair" unless mapping.size == 1
  @local_key = mapping.keys.first
  @foreign_key = mapping.fetch(@local_key)
  @eager_loaders = EagerLoaders::Context.new(@model)
  instance_eval(&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/ad_hoc_base.rb', line 10

def name
  @name
end

Instance Method Details

#run(rows, query_logger: 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)


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/occams-record/eager_loaders/ad_hoc_base.rb', line 39

def run(rows, query_logger: nil)
  calc_ids(rows) { |ids|
    assoc = if ids.any?
              binds = @binds.merge({:ids => ids})
              RawQuery.new(@sql, binds, use: @use, eager_loaders: @eager_loaders, query_logger: query_logger).run
            else
              []
            end
    merge! assoc, rows
  }
end