Class: N1Loader::ArLazyPreload::ContextAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/n1_loader/ar_lazy_preload/context_adapter.rb

Overview

Context adapter for injected N1Loader loaders.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ ContextAdapter

Returns a new instance of ContextAdapter.



11
12
13
# File 'lib/n1_loader/ar_lazy_preload/context_adapter.rb', line 11

def initialize(context)
  @context = context
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



7
8
9
# File 'lib/n1_loader/ar_lazy_preload/context_adapter.rb', line 7

def context
  @context
end

Instance Method Details

#perform_preloading(association_name) ⇒ Object

Initialize preloader for association_name with context builder callback. The callback will be executed when on records load.



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/n1_loader/ar_lazy_preload/context_adapter.rb', line 24

def perform_preloading(association_name)
  context_setup = lambda { |records|
    AssociatedContextBuilder.prepare(
      parent_context: self,
      association_name: association_name,
      records: records
    )
  }

  N1Loader::Preloader.new(records, context_setup).preload(association_name)
end

#try_preload_lazily(association_name) ⇒ Object

Assign initialized preloader to association_name in case it wasn’t yet preloaded within the given context.



16
17
18
19
20
# File 'lib/n1_loader/ar_lazy_preload/context_adapter.rb', line 16

def try_preload_lazily(association_name)
  return unless context&.send(:association_needs_preload?, association_name)

  perform_preloading(association_name)
end