Class: N1Loader::Loader
- Inherits:
-
Object
- Object
- N1Loader::Loader
- Includes:
- 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
Returns a new instance of Loader.
42 43 44 45 |
# File 'lib/n1_loader/core/loader.rb', line 42 def initialize(elements, **args) @elements = elements @args = args end |
Class Attribute Details
.arguments ⇒ Object (readonly)
Returns the value of attribute arguments.
10 11 12 |
# File 'lib/n1_loader/core/loader.rb', line 10 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.
21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/n1_loader/core/loader.rb', line 21 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.
34 35 36 37 38 39 |
# File 'lib/n1_loader/core/loader.rb', line 34 def cache_key(&block) define_method(:cache_key) do check_arguments! instance_exec(&block) end end |
Instance Method Details
#cache_key ⇒ Object
56 57 58 59 |
# File 'lib/n1_loader/core/loader.rb', line 56 def cache_key check_arguments! args.values.map(&:object_id) end |
#for(element) ⇒ Object
47 48 49 50 51 52 53 54 |
# File 'lib/n1_loader/core/loader.rb', line 47 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 |