Class: N1Loader::Loader
- Inherits:
-
Object
- Object
- N1Loader::Loader
- Includes:
- MonitorMixin, ArLazyPreload::LoaderPatch
- Defined in:
- lib/n1_loader/core/loader.rb
Overview
Loader that performs the loading.
Subclasses must define perform method that accepts single argument and returns hash where key is the element and value is what we want to load.
Constant Summary collapse
- UnsupportedArLazyPreload =
Raised when a single object without ArLazyPreload context support was passed to an isolated loader.
Class.new(StandardError)
Class Attribute Summary collapse
-
.arguments ⇒ Object
readonly
Returns the value of attribute arguments.
Attributes included from ArLazyPreload::LoaderPatch
Class Method Summary collapse
-
.argument(name, **opts) ⇒ Object
Defines an argument that can be accessed within the loader.
-
.cache_key(&block) ⇒ Object
Defines a custom cache key that is calculated for passed arguments.
Instance Method Summary collapse
- #cache_key ⇒ Object
- #for(element) ⇒ Object
-
#initialize(elements, **args) ⇒ Loader
constructor
A new instance of Loader.
Constructor Details
#initialize(elements, **args) ⇒ Loader
44 45 46 47 |
# File 'lib/n1_loader/core/loader.rb', line 44 def initialize(elements, **args) @elements = elements @args = args end |
Class Attribute Details
.arguments ⇒ Object (readonly)
Returns the value of attribute arguments.
12 13 14 |
# File 'lib/n1_loader/core/loader.rb', line 12 def arguments @arguments end |
Class Method Details
.argument(name, **opts) ⇒ Object
Defines an argument that can be accessed within the loader.
First defined argument will have the value of first passed argument, meaning the order is important.
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/n1_loader/core/loader.rb', line 23 def argument(name, **opts) opts[:optional] = true if opts[:default] @arguments ||= [] define_method(name) do args.fetch(name) { args[name] = opts[:default]&.call } end @arguments << opts.merge(name: name) end |
.cache_key(&block) ⇒ Object
Defines a custom cache key that is calculated for passed arguments.
36 37 38 39 40 41 |
# File 'lib/n1_loader/core/loader.rb', line 36 def cache_key(&block) define_method(:cache_key) do check_arguments! instance_exec(&block) end end |
Instance Method Details
#cache_key ⇒ Object
58 59 60 61 |
# File 'lib/n1_loader/core/loader.rb', line 58 def cache_key check_arguments! args.values.map(&:object_id) end |
#for(element) ⇒ Object
49 50 51 52 53 54 55 56 |
# File 'lib/n1_loader/core/loader.rb', line 49 def for(element) if loaded.empty? && elements.any? raise NotFilled, "Nothing was preloaded, perhaps you forgot to use fulfill method" end raise NotLoaded, "The data was not preloaded for the given element" unless loaded.key?(element) loaded[element] end |