Skip to content

Commit

Permalink
Feature skip_auto_preload
Browse files Browse the repository at this point in the history
  • Loading branch information
OuYangJinTing committed Jul 17, 2020
1 parent 58d27a4 commit bf94bc2
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/ar_lazy_preload/active_record/association.rb
Expand Up @@ -4,7 +4,7 @@ module ArLazyPreload
# ActiveRecord::Association patch with a hook for lazy preloading
module Association
def load_target
owner.try_preload_lazily(reflection.name)
owner.try_preload_lazily(reflection.name) unless owner.auto_preload == false
super
end
end
Expand Down
6 changes: 6 additions & 0 deletions lib/ar_lazy_preload/active_record/base.rb
Expand Up @@ -8,7 +8,13 @@ def self.included(base)
end

attr_accessor :lazy_preload_context
attr_reader :auto_preload

delegate :try_preload_lazily, to: :lazy_preload_context, allow_nil: true

def skip_auto_preload
@auto_preload = false
self
end
end
end
12 changes: 12 additions & 0 deletions spec/ar_lazy_preload/ar_lazy_preload_spec.rb
Expand Up @@ -230,4 +230,16 @@
end.to make_database_queries(count: 2)
end
end

describe "skip_auto_preload" do
subject { Comment.threads.lazy_preload(:replies) }

# SELECT "comments".* FROM "comments"
# SELECT "comments".* FROM "comments" WHERE "comments"."parent_comment_id" = ?
it "only load own association" do
expect do
subject.map { |comment| comment.skip_auto_preload.reply_ids }
end.to make_database_queries(matching: '"comments"."parent_comment_id" = ?')
end
end
end
11 changes: 10 additions & 1 deletion spec/ar_lazy_preload/auto_preload_spec.rb
Expand Up @@ -10,15 +10,24 @@
let!(:comment1) { create(:comment, user: user1, post: post) }
let!(:comment1) { create(:comment, user: user2, post: post) }

before(:all) { ArLazyPreload.config.auto_preload = true }
before(:each) { ArLazyPreload.config.auto_preload = true }

describe "auto preloading" do

subject { Comment.all }

# SELECT "comments".* FROM "comments"
# SELECT "users".* FROM "users" WHERE "users"."id" IN (...)
it "loads association automatically" do
expect { subject.each { |comment| comment.user&.id } }.to make_database_queries(count: 2)
end

# SELECT "comments".* FROM "comments"
# SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?
it "only load own association" do
expect do
subject.each { |comment| comment.skip_auto_preload.user&.id }
end.to make_database_queries(matching: '"users"."id" = ?')
end
end
end

0 comments on commit bf94bc2

Please sign in to comment.