salsify / goldiloader

Just the right amount of Rails eager loading

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Goldiloader don't preload data

biow0lf opened this issue · comments

Hi,

I configure goldiloader with Goldiloader.globally_enabled = false via rails initializer in config/initializers/goldiloader.rb:

# frozen_string_literal: true

Goldiloader.globally_enabled = false

and it doesn't preload data in blocks. For example:

def blueprints
  Goldiloader.enabled? # => false

  Goldiloader.enabled do
    Goldiloader.enabled? # => true

    ::Eve::Blueprint.order(:type_id) # here, goldiloader should preload data, but not.
  end
end

Changing Goldiloader.globally_enabled in initiliazer to true, "fixing" problem.

As I understand documentation, if I set Goldiloader.globally_enabled to true, goldiloader works.
If I set Goldiloader.globally_enabled to false, goldiloader disabled until I run anything in Goldiloader.enabled block.

Versions:

* rails (7.0.0.alpha2)
* goldiloader (4.1.2)

It looks like the block with Goldiloader enabled is creating an ActiveRecord::Relation but isn't actually trigger the execution of that relation or any associated models. Goldiloader only preloads an association when it's accessed so you'll need to make sure Goldiloader is enabled at that point. For example:

Goldiloader.enabled do
  blueprints = ::Eve::Blueprint.order(:type_id)
  blueprints.each do |blueprint|
    ## access an association to trigger eager loading of the association on all of the blueprints loaded in the previous step
    blueprint.author
  end
end

In practice this means you need Goldiloader to be enabled for a pretty broad scope (e.g. for the duration of an entire controller action or background job) to be useful.