Module: AdvancedAR::ArbitraryPrefetch::ActiveRecordRelationPatch

Defined in:
lib/advanced_ar/arbitrary_prefetch.rb

Instance Method Summary collapse

Instance Method Details

#add_prefetches!(kwargs) ⇒ Object



103
104
105
106
107
108
109
110
111
112
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 103

def add_prefetches!(kwargs)
  return unless kwargs.present?

  assert_mutability!
  @values[:prefetches] ||= {}
  kwargs.each do |attr, opts|
    @values[:prefetches][attr] = normalize_options(attr, opts)
  end
  self
end

#exec_queriesObject



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 82

def exec_queries
  return super if loaded?

  records = super
  preloader = nil
  (@values[:prefetches] || {}).each do |_key, opts|
    pfc = PrefetcherContext.new(model, opts)
    pfc.link_models(records)

    unless defined?(Goldiloader)
      preloader ||= build_preloader
      preloader.preload(records, opts[:attribute])
    end
  end
  records
end

#normalize_options(attr, opts) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 114

def normalize_options(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



99
100
101
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 99

def prefetch(**kwargs)
  spawn.add_prefetches!(kwargs)
end