module Goldiloader::CustomPreloads
Public Class Methods
new()
click to toggle source
Calls superclass method
# File lib/goldiloader/custom_preloads.rb, line 5 def initialize super @custom_preloads = nil end
Public Instance Methods
preloaded(model, cache_name:, key:, &block)
click to toggle source
# File lib/goldiloader/custom_preloads.rb, line 10 def preloaded(model, cache_name:, key:, &block) unless preloaded?(cache_name) ids = models.map do |record| key_from_record(record, key) end # We're using instance_exec instead of a simple yield to make sure that the # given block does not have any references to the model instance as this might # lead to unexpected results. The block will be executed in the context of the # class of the model instead. block_context = models.first.class preloaded_hash = block_context.instance_exec(ids, &block) store_preloaded(cache_name, preloaded_hash) end fetch_preloaded(cache_name, model, key: key) end
Private Instance Methods
fetch_preloaded(cache_name, instance, key:)
click to toggle source
# File lib/goldiloader/custom_preloads.rb, line 45 def fetch_preloaded(cache_name, instance, key:) @custom_preloads&.dig(cache_name, key_from_record(instance, key)) end
key_from_record(record, key_or_key_list)
click to toggle source
# File lib/goldiloader/custom_preloads.rb, line 29 def key_from_record(record, key_or_key_list) if key_or_key_list.is_a?(Array) # allow passing an array of keys that will be collected from the record key_or_key_list.map do |key| record.public_send(key) end else record.public_send(key_or_key_list) end end
preloaded?(cache_name)
click to toggle source
# File lib/goldiloader/custom_preloads.rb, line 49 def preloaded?(cache_name) @custom_preloads&.key?(cache_name) end
store_preloaded(cache_name, preloaded_hash)
click to toggle source
# File lib/goldiloader/custom_preloads.rb, line 40 def store_preloaded(cache_name, preloaded_hash) @custom_preloads ||= {} @custom_preloads[cache_name] = preloaded_hash end