Module: Miscellany::ArbitraryPrefetch::ActiveRecordPatches::RelationPatch
- Defined in:
- lib/miscellany/active_record/arbitrary_prefetch.rb
Instance Method Summary collapse
- #add_prefetches!(kwargs) ⇒ Object
- #exec_queries ⇒ Object
- #normalize_prefetch_options(attr, opts) ⇒ Object
- #prefetch(**kwargs) ⇒ Object
Instance Method Details
#add_prefetches!(kwargs) ⇒ Object
104 105 106 107 108 109 110 111 112 113 |
# File 'lib/miscellany/active_record/arbitrary_prefetch.rb', line 104 def add_prefetches!(kwargs) return unless kwargs.present? assert_mutability! @values[:prefetches] ||= {} kwargs.each do |attr, opts| @values[:prefetches][attr] = (attr, opts) end self end |
#exec_queries ⇒ Object
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/miscellany/active_record/arbitrary_prefetch.rb', line 81 def exec_queries return super if loaded? records = super (@values[:prefetches] || {}).each do |_key, opts| pfc = PrefetcherContext.new(model, opts) pfc.link_models(records) unless defined?(Goldiloader) && Goldiloader.enabled? if PRE_RAILS_6_2 ::ActiveRecord::Associations::Preloader.new.preload(records, [opts[:attribute]]) else ::ActiveRecord::Associations::Preloader.new(records: records, associations: [opts[:attribute]]).call end end end records end |
#normalize_prefetch_options(attr, opts) ⇒ Object
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
# File 'lib/miscellany/active_record/arbitrary_prefetch.rb', line 115 def (attr, opts) norm = if opts.is_a?(Array) { relation: opts[0], queryset: opts[1] } elsif opts.is_a?(ActiveRecord::Relation) rel_name = opts.model.name.underscore rel = (model.reflections[rel_name] || model.reflections[rel_name.pluralize])&.name { relation: rel, queryset: opts } else opts end norm[:attribute] = attr norm[:type] ||= (attr.to_s.pluralize == attr.to_s) ? :has_many : :has_one norm end |
#prefetch(**kwargs) ⇒ Object
100 101 102 |
# File 'lib/miscellany/active_record/arbitrary_prefetch.rb', line 100 def prefetch(**kwargs) spawn.add_prefetches!(kwargs) end |