Module: N1Loader::Loadable

Includes:
ArLazyPreload::Loadable, Goldiloader::Loadable
Included in:
ActiveRecord::Base
Defined in:
lib/n1_loader/core/loadable.rb

Overview

The module to be included to the class to define associated loaders.

class Example
include N1Loader::Loadable

# with inline loader
n1_optimized :something do
  def perform(elements)
    elements.each { |element| fulfill(element, element.calculate_something) }
  end
end

# with custom loader
n1_optimized :something, MyLoader
end

# custom loader
class MyLoader < N1Loader::Loader
def perform(elements)
  elements.each { |element| fulfill(element, element.calculate_something) }
end
end

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



66
67
68
# File 'lib/n1_loader/core/loadable.rb', line 66

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#n1_bind_to(collection) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/n1_loader/core/loadable.rb', line 35

def n1_bind_to(collection)
  unless collection.is_a?(Array) && collection.any? do |obj|
    obj == self || obj.equal?(self)
  end

    raise InvalidBinding,
          "assigned collection should be array and include object"
  end

  @n1_binding = collection
end

#n1_bind_to?Boolean

Returns:



47
48
49
# File 'lib/n1_loader/core/loadable.rb', line 47

def n1_bind_to?
  !@n1_binding.nil?
end

#n1_clear_cacheObject



59
60
61
62
63
64
# File 'lib/n1_loader/core/loadable.rb', line 59

def n1_clear_cache
  @n1_binding = nil
  self.class.n1_loaders.each_key do |name|
    n1_loaders[name] = nil
  end
end

#n1_loader(name) ⇒ Object



31
32
33
# File 'lib/n1_loader/core/loadable.rb', line 31

def n1_loader(name)
  n1_loaders[name]
end

#n1_loader_reload(name) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/n1_loader/core/loadable.rb', line 51

def n1_loader_reload(name)
  elements = @n1_binding || [self]
  collection = LoaderCollection.new(self.class.n1_loaders[name], elements)

  @n1_binding&.each { |el| el.n1_loaders[name] = collection if el.respond_to?(:n1_loaders) }
  n1_loaders[name] = collection
end

#n1_loadersObject



27
28
29
# File 'lib/n1_loader/core/loadable.rb', line 27

def n1_loaders
  @n1_loaders ||= {}
end