repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/support/rack_double.rb | spec/support/rack_double.rb | # frozen_string_literal: true
module Support
class AppDouble
def call(_env)
env = @env
[status, headers, response]
end
attr_writer :status
attr_writer :headers
def headers
@headers ||= { 'Content-Type' => 'text/html' }
@headers
end
attr_writer :response
private
def status
@status || 200
end
def response
@response || ResponseDouble.new
end
end
class ResponseDouble
def initialize(actual_body = nil)
@actual_body = actual_body
end
def body
@body ||= '<html><head></head><body></body></html>'
end
attr_writer :body
def each
yield body
end
def close; end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/integration/counter_cache_spec.rb | spec/integration/counter_cache_spec.rb | # frozen_string_literal: true
require 'spec_helper'
if !mongoid? && active_record?
describe Bullet::Detector::CounterCache do
before(:each) { Bullet.start_request }
after(:each) { Bullet.end_request }
it 'should need counter cache with all cities' do
Country.all.each { |country| country.cities.size }
expect(Bullet.collected_counter_cache_notifications).not_to be_empty
end
it 'should not need counter cache if already define counter_cache' do
Person.all.each { |person| person.pets.size }
expect(Bullet.collected_counter_cache_notifications).to be_empty
end
it 'should not need counter cache with only one object' do
Country.first.cities.size
expect(Bullet.collected_counter_cache_notifications).to be_empty
end
it 'should not need counter cache without size' do
Country.includes(:cities).each { |country| country.cities.empty? }
expect(Bullet.collected_counter_cache_notifications).to be_empty
end
if ActiveRecord::VERSION::MAJOR > 4
it 'should not need counter cache for has_many through' do
Client.all.each { |client| client.firms.size }
expect(Bullet.collected_counter_cache_notifications).to be_empty
end
else
it 'should need counter cache for has_many through' do
Client.all.each { |client| client.firms.size }
expect(Bullet.collected_counter_cache_notifications).not_to be_empty
end
end
it 'should not need counter cache with part of cities' do
Country.all.each { |country| country.cities.where(name: 'first').size }
expect(Bullet.collected_counter_cache_notifications).to be_empty
end
context 'disable' do
before { Bullet.counter_cache_enable = false }
after { Bullet.counter_cache_enable = true }
it 'should not detect counter cache' do
Country.all.each { |country| country.cities.size }
expect(Bullet.collected_counter_cache_notifications).to be_empty
end
end
context 'safelist' do
before { Bullet.add_safelist type: :counter_cache, class_name: 'Country', association: :cities }
after { Bullet.clear_safelist }
it 'should not detect counter cache' do
Country.all.each { |country| country.cities.size }
expect(Bullet.collected_counter_cache_notifications).to be_empty
end
end
describe 'with count' do
it 'should need counter cache' do
Country.all.each { |country| country.cities.count }
expect(Bullet.collected_counter_cache_notifications).not_to be_empty
end
it 'should notify even with counter cache' do
Person.all.each { |person| person.pets.count }
expect(Bullet.collected_counter_cache_notifications).not_to be_empty
end
if ActiveRecord::VERSION::MAJOR > 4
it 'should not need counter cache for has_many through' do
Client.all.each { |client| client.firms.count }
expect(Bullet.collected_counter_cache_notifications).to be_empty
end
else
it 'should need counter cache for has_many through' do
Client.all.each { |client| client.firms.count }
expect(Bullet.collected_counter_cache_notifications).not_to be_empty
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/integration/mongoid/association_spec.rb | spec/integration/mongoid/association_spec.rb | # frozen_string_literal: true
require 'spec_helper'
if mongoid?
describe Bullet::Detector::Association do
context 'embeds_many' do
context 'posts => users' do
it 'should detect nothing' do
Mongoid::Post.all.each { |post| post.users.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
context 'has_many' do
context 'posts => comments' do
it 'should detect non preload posts => comments' do
Mongoid::Post.all.each { |post| post.comments.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Mongoid::Post, :comments)
end
it 'should detect preload post => comments' do
Mongoid::Post.includes(:comments).each { |post| post.comments.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload post => comments' do
Mongoid::Post.includes(:comments).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Mongoid::Post, :comments)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect unused preload post => comments' do
Mongoid::Post.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'category => posts, category => entries' do
it 'should detect non preload with category => [posts, entries]' do
Mongoid::Category.all.each do |category|
category.posts.map(&:name)
category.entries.map(&:name)
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Mongoid::Category, :posts)
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Mongoid::Category, :entries)
end
it 'should detect preload with category => posts, but not with category => entries' do
Mongoid::Category.includes(:posts).each do |category|
category.posts.map(&:name)
category.entries.map(&:name)
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_detecting_unpreloaded_association_for(
Mongoid::Category,
:posts
)
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Mongoid::Category, :entries)
end
it 'should detect preload with category => [posts, entries]' do
Mongoid::Category.includes(:posts, :entries).each do |category|
category.posts.map(&:name)
category.entries.map(&:name)
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with category => [posts, entries]' do
Mongoid::Category.includes(:posts, :entries).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Mongoid::Category, :posts)
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Mongoid::Category, :entries)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with category => entries, but not with category => posts' do
Mongoid::Category.includes(:posts, :entries).each { |category| category.posts.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_unused_preload_associations_for(Mongoid::Category, :posts)
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Mongoid::Category, :entries)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'post => comment' do
it 'should detect unused preload with post => comments' do
Mongoid::Post.includes(:comments).each { |post| post.comments.first.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_unused_preload_associations_for(Mongoid::Post, :comments)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect preload with post => comments' do
Mongoid::Post.first.comments.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'scope preload_comments' do
it 'should detect preload post => comments with scope' do
Mongoid::Post.preload_comments.each { |post| post.comments.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with scope' do
Mongoid::Post.preload_comments.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Mongoid::Post, :comments)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
context 'belongs_to' do
context 'comment => post' do
it 'should detect non preload with comment => post' do
Mongoid::Comment.all.each { |comment| comment.post.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Mongoid::Comment, :post)
end
it 'should detect preload with one comment => post' do
Mongoid::Comment.first.post.name
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect preload with comment => post' do
Mongoid::Comment.includes(:post).each { |comment| comment.post.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect preload with comment => post' do
Mongoid::Comment.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with comments => post' do
Mongoid::Comment.includes(:post).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Mongoid::Comment, :post)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
context 'has_one' do
context 'company => address' do
if Mongoid::VERSION !~ /\A3.0/
it 'should detect non preload association' do
Mongoid::Company.all.each { |company| company.address.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(
Mongoid::Company,
:address
)
end
end
it 'should detect preload association' do
Mongoid::Company.includes(:address).each { |company| company.address.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect preload association' do
Mongoid::Company.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload association' do
criteria = Mongoid::Company.includes(:address)
criteria.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Mongoid::Company, :address)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
context 'call one association that in possible objects' do
it 'should not detect preload association' do
Mongoid::Post.all
Mongoid::Post.first.comments.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/integration/active_record/association_spec.rb | spec/integration/active_record/association_spec.rb | # frozen_string_literal: true
require 'spec_helper'
if active_record?
describe Bullet::Detector::Association, 'has_many' do
context 'post => comments' do
it 'should detect non preload post => comments' do
Post.all.each { |post| post.comments.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :comments)
end
it 'should detect non preload post => comments for find_by_sql' do
Post.find_by_sql('SELECT * FROM posts').each { |post| post.comments.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :comments)
end
it 'should detect preload with post => comments' do
Post.includes(:comments).each { |post| post.comments.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload post => comments' do
Post.includes(:comments).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Post, :comments)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect unused preload post => comments' do
Post.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect non preload comment => post with inverse_of' do
Post.includes(:comments).each do |post|
post.comments.each do |comment|
comment.name
comment.post.name
end
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect non preload comment => post with inverse_of from a query' do
Post.first.comments.find_each do |comment|
comment.name
comment.post.name
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Post.first.comments.count).not_to eq(0)
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect non preload post => comments with empty?' do
Post.all.each { |post| post.comments.empty? }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :comments)
end
it 'should detect non preload post => comments with include?' do
comment = Comment.last
Post.all.each { |post| post.comments.include?(comment) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :comments)
end
if ActiveRecord::VERSION::MAJOR != 4 && ActiveRecord::VERSION::MINOR != 0
it 'should not detect unused preload post => comment with empty?' do
Post.includes(:comments).each { |post| post.comments.empty? }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
it 'should not detect unused preload post => comment with count' do
Post.includes(:comments).each { |post| post.comments.count }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect non preload post => comments with count' do
Post.all.each { |post| post.comments.count }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :comments)
end
context 'inside Fiber' do
it 'should detect non preload post => comments' do
fiber =
Fiber.new do
Post.all.each { |post| post.comments.map(&:name) }
end
fiber.resume
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :comments)
end
end
end
context 'category => posts => comments' do
it 'should detect non preload category => posts => comments' do
Category.all.each { |category| category.posts.each { |post| post.comments.map(&:name) } }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Category, :posts)
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :comments)
end
it 'should detect preload category => posts, but no post => comments' do
Category.includes(:posts).each { |category| category.posts.each { |post| post.comments.map(&:name) } }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_detecting_unpreloaded_association_for(Category, :posts)
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :comments)
end
it 'should detect preload with category => posts => comments' do
Category.includes(posts: :comments).each { |category| category.posts.each { |post| post.comments.map(&:name) } }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect preload with category => posts => comments with posts.id > 0' do
Category.includes(posts: :comments).where('posts.id > 0').references(:posts).each do |category|
category.posts.each { |post| post.comments.map(&:name) }
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with category => posts => comments' do
Category.includes(posts: :comments).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Post, :comments)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with post => comments, no category => posts' do
Category.includes(posts: :comments).each { |category| category.posts.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Post, :comments)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'category => posts, category => entries' do
it 'should detect non preload with category => [posts, entries]' do
Category.all.each do |category|
category.posts.map(&:name)
category.entries.map(&:name)
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Category, :posts)
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Category, :entries)
end
it 'should detect preload with category => posts, but not with category => entries' do
Category.includes(:posts).each do |category|
category.posts.map(&:name)
category.entries.map(&:name)
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_detecting_unpreloaded_association_for(Category, :posts)
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Category, :entries)
end
it 'should detect preload with category => [posts, entries]' do
Category.includes(%i[posts entries]).each do |category|
category.posts.map(&:name)
category.entries.map(&:name)
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with category => [posts, entries]' do
Category.includes(%i[posts entries]).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Category, :posts)
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Category, :entries)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with category => entries, but not with category => posts' do
Category.includes(%i[posts entries]).each { |category| category.posts.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_unused_preload_associations_for(Category, :posts)
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Category, :entries)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'post => comment' do
it 'should detect unused preload with post => comments' do
Post.includes(:comments).each { |post| post.comments.first&.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_unused_preload_associations_for(Post, :comments)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect preload with post => comments' do
Post.first.comments.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect unused preload with category => posts' do
category = Category.first
category.draft_post.destroy!
post = category.draft_post
post.update!(link: true)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
Support::SqliteSeed.setup_db
Support::SqliteSeed.seed_db
end
end
context 'category => posts => writer' do
it 'should not detect unused preload associations' do
category = Category.includes(posts: :writer).order('id DESC').find_by_name('first')
category.posts.map do |post|
post.name
post.writer.name
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_unused_preload_associations_for(Category, :posts)
expect(Bullet::Detector::Association).not_to be_unused_preload_associations_for(Post, :writer)
end
end
context 'scope for_category_name' do
it 'should detect preload with post => category' do
Post.in_category_name('first').references(:categories).each { |post| post.category.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not be unused preload post => category' do
Post.in_category_name('first').references(:categories).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'scope preload_comments' do
it 'should detect preload post => comments with scope' do
Post.preload_comments.each { |post| post.comments.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with scope' do
Post.preload_comments.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Post, :comments)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
describe Bullet::Detector::Association, 'belongs_to' do
context 'comment => post' do
it 'should detect non preload with comment => post' do
Comment.all.each { |comment| comment.post.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Comment, :post)
end
it 'should detect preload with one comment => post' do
Comment.first.post.name
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect preload with comment => post' do
Comment.includes(:post).each { |comment| comment.post.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect preload with comment => post' do
Comment.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload with comment => post' do
Comment.includes(:post).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Comment, :post)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
context 'in an after_save' do
around do |example|
new_post = Post.new(category: Category.first)
new_post.trigger_after_save = true
new_post.save!
example.run
new_post.destroy
end
it 'should not detect newly assigned object' do
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
context 'comment => post => category' do
it 'should detect non preload association with comment => post' do
Comment.all.each { |comment| comment.post.category.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Comment, :post)
end
it 'should not detect non preload association with only one comment' do
Comment.first.post.category.name
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect non preload association with post => category' do
Comment.includes(:post).each { |comment| comment.post.category.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :category)
end
it 'should not detect unpreload association' do
Comment.includes(post: :category).each { |comment| comment.post.category.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'comment => author, post => writer' do
it 'should detect non preloaded writer' do
Comment.includes(%i[author post]).where(['base_users.id = ?', BaseUser.first]).references(:base_users)
.each { |comment| comment.post.writer.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Post, :writer)
end
it 'should detect unused preload with comment => author' do
Comment.includes([:author, { post: :writer }]).where(['base_users.id = ?', BaseUser.first]).references(
:base_users
).each { |comment| comment.post.writer.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect non preloading with writer => newspaper' do
Comment.includes(post: :writer).where("posts.name like '%first%'").references(:posts).each do |comment|
comment.post.writer.newspaper.name
end
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Writer, :newspaper)
end
it 'should not raise a stack error from posts to category' do
expect { Comment.includes(post: :category).each { |com| com.post.category } }
.not_to raise_error
end
end
end
describe Bullet::Detector::Association, 'has_and_belongs_to_many' do
context 'posts <=> deals' do
it 'should detect preload associations with join tables that have identifier' do
Post.includes(:deals).each { |post| post.deals.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'students <=> teachers' do
it 'should detect non preload associations' do
Student.all.each { |student| student.teachers.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Student, :teachers)
end
it 'should detect preload associations' do
Student.includes(:teachers).each { |student| student.teachers.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload associations' do
Student.includes(:teachers).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Student, :teachers)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect no unused preload associations' do
Student.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect non preload student => teachers with empty?' do
Student.all.each { |student| student.teachers.empty? }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Student, :teachers)
end
end
context 'user => roles' do
it 'should detect preload associations' do
User.first.roles.includes(:resource).each { |role| role.resource }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
describe Bullet::Detector::Association, 'has_many :through' do
context 'firm => clients' do
it 'should detect non preload associations' do
Firm.all.each { |firm| firm.clients.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Firm, :clients)
end
it 'should detect preload associations' do
Firm.preload(:clients).each { |firm| firm.clients.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect eager load association' do
Firm.eager_load(:clients).each { |firm| firm.clients.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect preload associations' do
Firm.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload associations' do
Firm.includes(:clients).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Firm, :clients)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
context 'firm => clients => groups' do
it 'should detect non preload associations' do
Firm.all.each { |firm| firm.groups.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Firm, :groups)
end
it 'should detect preload associations' do
Firm.preload(:groups).each { |firm| firm.groups.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect eager load associations' do
Firm.eager_load(:groups).each { |firm| firm.groups.map(&:name) }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect preload associations' do
Firm.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload associations' do
Firm.includes(:groups).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Firm, :groups)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
describe Bullet::Detector::Association, 'has_one' do
context 'company => address' do
it 'should detect non preload association' do
Company.all.each { |company| company.address.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(Company, :address)
end
it 'should detect preload association' do
Company.includes(:address).each { |company| company.address.name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect preload association' do
Company.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload association' do
Company.includes(:address).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(Company, :address)
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
end
describe Bullet::Detector::Association, 'has_one => has_many' do
it 'should not detect preload association' do
user = User.first
user.submission.replies.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
end
describe Bullet::Detector::Association, 'has_one :through' do
context 'user => attachment' do
it 'should detect non preload associations' do
User.all.each { |user| user.submission_attachment.file_name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_detecting_unpreloaded_association_for(User, :submission_attachment)
end
it 'should not detect preload associations with includes' do
User.includes(:submission_attachment).each { |user| user.submission_attachment.file_name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect preload associations with eager_load' do
User.eager_load(:submission_attachment).each { |user| user.submission_attachment.file_name }
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should not detect preload associations' do
User.all.map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).not_to be_has_unused_preload_associations
expect(Bullet::Detector::Association).to be_completely_preloading_associations
end
it 'should detect unused preload associations' do
User.includes(:submission_attachment).map(&:name)
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
expect(Bullet::Detector::Association).to be_unused_preload_associations_for(User, :submission_attachment)
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | true |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/student.rb | spec/models/student.rb | # frozen_string_literal: true
class Student < ActiveRecord::Base
has_and_belongs_to_many :teachers
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/entry.rb | spec/models/entry.rb | # frozen_string_literal: true
class Entry < ActiveRecord::Base
belongs_to :category
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/base_user.rb | spec/models/base_user.rb | # frozen_string_literal: true
class BaseUser < ActiveRecord::Base
has_many :comments
has_many :posts
belongs_to :newspaper
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/group.rb | spec/models/group.rb | # frozen_string_literal: true
class Group < ActiveRecord::Base
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/relationship.rb | spec/models/relationship.rb | # frozen_string_literal: true
class Relationship < ActiveRecord::Base
belongs_to :firm
belongs_to :client
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/page.rb | spec/models/page.rb | # frozen_string_literal: true
class Page < Document
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/pet.rb | spec/models/pet.rb | # frozen_string_literal: true
class Pet < ActiveRecord::Base
belongs_to :person, counter_cache: true
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/city.rb | spec/models/city.rb | # frozen_string_literal: true
class City < ActiveRecord::Base
belongs_to :country
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/country.rb | spec/models/country.rb | # frozen_string_literal: true
class Country < ActiveRecord::Base
has_many :cities
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/category.rb | spec/models/category.rb | # frozen_string_literal: true
class Category < ActiveRecord::Base
has_many :posts, inverse_of: :category
has_many :entries
has_many :users
def draft_post
posts.draft.first_or_create
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/teacher.rb | spec/models/teacher.rb | # frozen_string_literal: true
class Teacher < ActiveRecord::Base
has_and_belongs_to_many :students
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/address.rb | spec/models/address.rb | # frozen_string_literal: true
class Address < ActiveRecord::Base
belongs_to :company
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/author.rb | spec/models/author.rb | # frozen_string_literal: true
class Author < ActiveRecord::Base
has_many :documents
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/comment.rb | spec/models/comment.rb | # frozen_string_literal: true
class Comment < ActiveRecord::Base
belongs_to :post, inverse_of: :comments
belongs_to :author, class_name: 'BaseUser'
validates :post, presence: true
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/writer.rb | spec/models/writer.rb | # frozen_string_literal: true
class Writer < BaseUser
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/attachment.rb | spec/models/attachment.rb | # frozen_string_literal: true
class Attachment < ActiveRecord::Base
belongs_to :submission
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/post.rb | spec/models/post.rb | # frozen_string_literal: true
class Post < ActiveRecord::Base
belongs_to :category, inverse_of: :posts
belongs_to :writer
has_many :comments, inverse_of: :post
has_and_belongs_to_many :deals
validates :category, presence: true
scope :preload_comments, -> { includes(:comments) }
scope :in_category_name, ->(name) { where(['categories.name = ?', name]).includes(:category) }
scope :draft, -> { where(active: false) }
def link=(*)
comments.new
end
# see association_spec.rb 'should not detect newly assigned object in an after_save'
attr_accessor :trigger_after_save
after_save do
next unless trigger_after_save
temp_comment = Comment.new(post: self)
# this triggers self to be "possible", even though it's
# not saved yet
temp_comment.post
# category should NOT whine about not being pre-loaded, because
# it's obviously attached to a new object
category
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/submission.rb | spec/models/submission.rb | # frozen_string_literal: true
class Submission < ActiveRecord::Base
belongs_to :user
has_many :replies
has_one :attachment
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/folder.rb | spec/models/folder.rb | # frozen_string_literal: true
class Folder < Document
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/client.rb | spec/models/client.rb | # frozen_string_literal: true
class Client < ActiveRecord::Base
belongs_to :group
has_many :relationships
has_many :firms, through: :relationships
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/role.rb | spec/models/role.rb | # frozen_string_literal: true
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
belongs_to :resource, polymorphic: true
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/newspaper.rb | spec/models/newspaper.rb | # frozen_string_literal: true
class Newspaper < ActiveRecord::Base
has_many :writers, class_name: 'BaseUser'
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/person.rb | spec/models/person.rb | # frozen_string_literal: true
class Person < ActiveRecord::Base
has_many :pets
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/reply.rb | spec/models/reply.rb | # frozen_string_literal: true
class Reply < ActiveRecord::Base
belongs_to :submission
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/deal.rb | spec/models/deal.rb | # frozen_string_literal: true
class Deal < ActiveRecord::Base
has_and_belongs_to_many :posts
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/firm.rb | spec/models/firm.rb | # frozen_string_literal: true
class Firm < ActiveRecord::Base
has_many :relationships
has_many :clients, through: :relationships
has_many :groups, through: :clients
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/document.rb | spec/models/document.rb | # frozen_string_literal: true
class Document < ActiveRecord::Base
has_many :children, class_name: 'Document', foreign_key: 'parent_id'
belongs_to :parent, class_name: 'Document', foreign_key: 'parent_id'
belongs_to :author
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/company.rb | spec/models/company.rb | # frozen_string_literal: true
class Company < ActiveRecord::Base
has_one :address
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/user.rb | spec/models/user.rb | # frozen_string_literal: true
class User < ActiveRecord::Base
has_one :submission
has_one :submission_attachment, through: :submission, source: :attachment, class_name: 'Attachment'
belongs_to :category
has_and_belongs_to_many :roles
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/mongoid/entry.rb | spec/models/mongoid/entry.rb | # frozen_string_literal: true
class Mongoid::Entry
include Mongoid::Document
field :name
belongs_to :category, class_name: 'Mongoid::Category'
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/mongoid/category.rb | spec/models/mongoid/category.rb | # frozen_string_literal: true
class Mongoid::Category
include Mongoid::Document
field :name
has_many :posts, class_name: 'Mongoid::Post'
has_many :entries, class_name: 'Mongoid::Entry'
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/mongoid/address.rb | spec/models/mongoid/address.rb | # frozen_string_literal: true
class Mongoid::Address
include Mongoid::Document
field :name
belongs_to :company, class_name: 'Mongoid::Company'
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/mongoid/comment.rb | spec/models/mongoid/comment.rb | # frozen_string_literal: true
class Mongoid::Comment
include Mongoid::Document
field :name
belongs_to :post, class_name: 'Mongoid::Post'
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/mongoid/post.rb | spec/models/mongoid/post.rb | # frozen_string_literal: true
class Mongoid::Post
include Mongoid::Document
field :name
has_many :comments, class_name: 'Mongoid::Comment'
belongs_to :category, class_name: 'Mongoid::Category'
embeds_many :users, class_name: 'Mongoid::User'
scope :preload_comments, -> { includes(:comments) }
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/mongoid/company.rb | spec/models/mongoid/company.rb | # frozen_string_literal: true
class Mongoid::Company
include Mongoid::Document
field :name
has_one :address, class_name: 'Mongoid::Address'
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/models/mongoid/user.rb | spec/models/mongoid/user.rb | # frozen_string_literal: true
class Mongoid::User
include Mongoid::Document
field :name
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/stack_trace_filter_spec.rb | spec/bullet/stack_trace_filter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
RSpec.describe StackTraceFilter do
let(:dummy_class) { Class.new { extend StackTraceFilter } }
let(:root_path) { Dir.pwd }
let(:bundler_path) { Bundler.bundle_path }
describe '#caller_in_project' do
it 'gets the caller in the project' do
expect(dummy_class).to receive(:call_stacks).and_return(
{
'Post:1' => [
File.join(root_path, 'lib/bullet.rb'),
File.join(root_path, 'vendor/uniform_notifier.rb'),
File.join(bundler_path, 'rack.rb')
]
}
)
expect(dummy_class.caller_in_project('Post:1')).to eq([File.join(root_path, 'lib/bullet.rb')])
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/rack_spec.rb | spec/bullet/rack_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
describe Rack do
let(:middleware) { Bullet::Rack.new app }
let(:app) { Support::AppDouble.new }
context '#html_request?' do
it 'should be true if Content-Type is text/html and http body contains html tag' do
headers = { 'Content-Type' => 'text/html' }
response = double(body: '<html><head></head><body></body></html>')
expect(middleware).to be_html_request(headers, response)
end
it 'should be true if Content-Type is text/html and http body contains html tag with attributes' do
headers = { 'Content-Type' => 'text/html' }
response = double(body: "<html attr='hello'><head></head><body></body></html>")
expect(middleware).to be_html_request(headers, response)
end
it 'should be false if there is no Content-Type header' do
headers = {}
response = double(body: '<html><head></head><body></body></html>')
expect(middleware).not_to be_html_request(headers, response)
end
it 'should be false if Content-Type is javascript' do
headers = { 'Content-Type' => 'text/javascript' }
response = double(body: '<html><head></head><body></body></html>')
expect(middleware).not_to be_html_request(headers, response)
end
end
context '#skip_html_injection?' do
let(:request) { double('request') }
it 'should return false if query_string is nil' do
allow(request).to receive(:env).and_return({ 'QUERY_STRING' => nil })
expect(middleware.skip_html_injection?(request)).to be_falsey
end
it 'should return false if query_string is empty' do
allow(request).to receive(:env).and_return({ 'QUERY_STRING' => '' })
expect(middleware.skip_html_injection?(request)).to be_falsey
end
it 'should return true if skip_html_injection parameter is true' do
allow(request).to receive(:env).and_return({ 'QUERY_STRING' => 'skip_html_injection=true' })
expect(middleware.skip_html_injection?(request)).to be_truthy
end
it 'should return false if skip_html_injection parameter is not true' do
allow(request).to receive(:env).and_return({ 'QUERY_STRING' => 'skip_html_injection=false' })
expect(middleware.skip_html_injection?(request)).to be_falsey
end
it 'should return false if skip_html_injection parameter is not present' do
allow(request).to receive(:env).and_return({ 'QUERY_STRING' => 'other_param=value' })
expect(middleware.skip_html_injection?(request)).to be_falsey
end
it 'should handle complex query strings' do
allow(request).to receive(:env).and_return({ 'QUERY_STRING' => 'param1=value1&skip_html_injection=true¶m2=value2' })
expect(middleware.skip_html_injection?(request)).to be_truthy
end
end
context 'empty?' do
it 'should be false if response is a string and not empty' do
response = double(body: '<html><head></head><body></body></html>')
expect(middleware).not_to be_empty(response)
end
it 'should be false if response is not found' do
response = ['Not Found']
expect(middleware).not_to be_empty(response)
end
it 'should be true if response body is empty' do
response = double(body: '')
expect(middleware).to be_empty(response)
end
it 'should be true if no response body' do
response = double
expect(middleware).to be_empty(response)
end
end
context '#call' do
context 'when Bullet is enabled' do
it 'should return original response body' do
expected_response = Support::ResponseDouble.new 'Actual body'
app.response = expected_response
_, _, response = middleware.call({})
expect(response).to eq(expected_response)
end
it 'should change response body if notification is active' do
expect(Bullet).to receive(:notification?).and_return(true)
expect(Bullet).to receive(:console_enabled?).and_return(true)
expect(Bullet).to receive(:gather_inline_notifications).and_return('<bullet></bullet>')
expect(Bullet).to receive(:perform_out_of_channel_notifications)
_, headers, response = middleware.call('Content-Type' => 'text/html')
expect(headers['Content-Length']).to eq('56')
expect(response).to eq(%w[<html><head></head><body><bullet></bullet></body></html>])
end
it 'should change response body if always_append_html_body is true' do
expect(Bullet).to receive(:always_append_html_body).and_return(true)
expect(Bullet).to receive(:console_enabled?).and_return(true)
expect(Bullet).to receive(:gather_inline_notifications).and_return('<bullet></bullet>')
expect(Bullet).to receive(:perform_out_of_channel_notifications)
_, headers, response = middleware.call('Content-Type' => 'text/html')
expect(headers['Content-Length']).to eq('56')
expect(response).to eq(%w[<html><head></head><body><bullet></bullet></body></html>])
end
it 'should set the right Content-Length if response body contains accents' do
response = Support::ResponseDouble.new
response.body = '<html><head></head><body>é</body></html>'
app.response = response
expect(Bullet).to receive(:notification?).and_return(true)
allow(Bullet).to receive(:console_enabled?).and_return(true)
expect(Bullet).to receive(:gather_inline_notifications).and_return('<bullet></bullet>')
_, headers, response = middleware.call('Content-Type' => 'text/html')
expect(headers['Content-Length']).to eq('58')
end
shared_examples 'inject notifiers' do
before do
allow(Bullet).to receive(:gather_inline_notifications).and_return('<bullet></bullet>')
allow(middleware).to receive(:xhr_script).and_return('<script></script>')
allow(middleware).to receive(:footer_note).and_return('footer')
expect(Bullet).to receive(:perform_out_of_channel_notifications)
end
it 'should change response body if add_footer is true' do
expect(Bullet).to receive(:add_footer).exactly(3).times.and_return(true)
_, headers, response = middleware.call('Content-Type' => 'text/html')
expect(headers['Content-Length']).to eq((73 + middleware.send(:footer_note).length).to_s)
expect(response).to eq(%w[<html><head></head><body>footer<bullet></bullet><script></script></body></html>])
end
it 'should change response body for html safe string if add_footer is true' do
expect(Bullet).to receive(:add_footer).exactly(3).times.and_return(true)
app.response =
Support::ResponseDouble.new.tap do |response|
response.body = ActiveSupport::SafeBuffer.new('<html><head></head><body></body></html>')
end
_, headers, response = middleware.call('Content-Type' => 'text/html')
expect(headers['Content-Length']).to eq((73 + middleware.send(:footer_note).length).to_s)
expect(response).to eq(%w[<html><head></head><body>footer<bullet></bullet><script></script></body></html>])
end
it 'should add the footer-text header for non-html requests when add_footer is true' do
allow(Bullet).to receive(:add_footer).at_least(:once).and_return(true)
allow(Bullet).to receive(:footer_info).and_return(['footer text'])
app.headers = { 'Content-Type' => 'application/json' }
_, headers, _response = middleware.call({})
expect(headers).to include('X-bullet-footer-text' => '["footer text"]')
end
it 'should change response body if console_enabled is true' do
expect(Bullet).to receive(:console_enabled?).and_return(true)
_, headers, response = middleware.call('Content-Type' => 'text/html')
expect(headers['Content-Length']).to eq('56')
expect(response).to eq(%w[<html><head></head><body><bullet></bullet></body></html>])
end
it 'should include CSP nonce in inline script if console_enabled and a CSP is applied' do
allow(Bullet).to receive(:add_footer).at_least(:once).and_return(true)
expect(Bullet).to receive(:console_enabled?).and_return(true)
allow(middleware).to receive(:xhr_script).and_call_original
nonce = '+t9/wTlgG6xbHxXYUaDNzQ=='
app.headers = {
'Content-Type' => 'text/html',
'Content-Security-Policy' => "default-src 'self' https:; script-src 'self' https: 'nonce-#{nonce}'"
}
_, headers, response = middleware.call('Content-Type' => 'text/html')
size = 56 + middleware.send(:footer_note, nonce).length + middleware.send(:xhr_script, nonce).length
expect(headers['Content-Length']).to eq(size.to_s)
end
it 'should include CSP nonce in inline script if console_enabled and a CSP (report only) is applied' do
allow(Bullet).to receive(:add_footer).at_least(:once).and_return(true)
expect(Bullet).to receive(:console_enabled?).and_return(true)
allow(middleware).to receive(:xhr_script).and_call_original
nonce = '+t9/wTlgG6xbHxXYUaDNzQ=='
app.headers = {
'Content-Type' => 'text/html',
'Content-Security-Policy-Report-Only' =>
"default-src 'self' https:; script-src 'self' https: 'nonce-#{nonce}'"
}
_, headers, response = middleware.call('Content-Type' => 'text/html')
size = 56 + middleware.send(:footer_note, nonce).length + middleware.send(:xhr_script, nonce).length
expect(headers['Content-Length']).to eq(size.to_s)
end
it 'should include CSP nonce in inline style if console_enabled and a CSP is applied' do
allow(Bullet).to receive(:add_footer).at_least(:once).and_return(true)
expect(Bullet).to receive(:console_enabled?).and_return(true)
allow(middleware).to receive(:xhr_script).and_call_original
nonce = '+t9/wTlgG6xbHxXYUaDNzQ=='
app.headers = {
'Content-Type' => 'text/html',
'Content-Security-Policy' => "default-src 'self' https:; style-src 'self' https: 'nonce-#{nonce}'"
}
_, headers, response = middleware.call('Content-Type' => 'text/html')
size = 56 + middleware.send(:footer_note, nonce).length + middleware.send(:xhr_script, nonce).length
expect(headers['Content-Length']).to eq(size.to_s)
end
it 'should include CSP nonce in inline style if console_enabled and a CSP (report only) is applied' do
allow(Bullet).to receive(:add_footer).at_least(:once).and_return(true)
expect(Bullet).to receive(:console_enabled?).and_return(true)
allow(middleware).to receive(:xhr_script).and_call_original
nonce = '+t9/wTlgG6xbHxXYUaDNzQ=='
app.headers = {
'Content-Type' => 'text/html',
'Content-Security-Policy-Report-Only' =>
"default-src 'self' https:; style-src 'self' https: 'nonce-#{nonce}'"
}
_, headers, response = middleware.call('Content-Type' => 'text/html')
size = 56 + middleware.send(:footer_note, nonce).length + middleware.send(:xhr_script, nonce).length
expect(headers['Content-Length']).to eq(size.to_s)
end
it 'should change response body for html safe string if console_enabled is true' do
expect(Bullet).to receive(:console_enabled?).and_return(true)
app.response =
Support::ResponseDouble.new.tap do |response|
response.body = ActiveSupport::SafeBuffer.new('<html><head></head><body></body></html>')
end
_, headers, response = middleware.call('Content-Type' => 'text/html')
expect(headers['Content-Length']).to eq('56')
expect(response).to eq(%w[<html><head></head><body><bullet></bullet></body></html>])
end
it 'should add headers for non-html requests when console_enabled is true' do
allow(Bullet).to receive(:console_enabled?).at_least(:once).and_return(true)
allow(Bullet).to receive(:text_notifications).and_return(['text notifications'])
app.headers = { 'Content-Type' => 'application/json' }
_, headers, _response = middleware.call({})
expect(headers).to include('X-bullet-console-text' => '["text notifications"]')
end
it "shouldn't change response body unnecessarily" do
expected_response = Support::ResponseDouble.new 'Actual body'
app.response = expected_response
_, _, response = middleware.call({})
expect(response).to eq(expected_response)
end
it "shouldn't add headers unnecessarily" do
app.headers = { 'Content-Type' => 'application/json' }
_, headers, _response = middleware.call({})
expect(headers).not_to include('X-bullet-footer-text')
expect(headers).not_to include('X-bullet-console-text')
end
context 'when skip_http_headers is enabled' do
before do
allow(Bullet).to receive(:skip_http_headers).and_return(true)
end
it 'should include the footer but not the xhr script tag if add_footer is true' do
expect(Bullet).to receive(:add_footer).at_least(:once).and_return(true)
_, headers, response = middleware.call({})
expect(headers['Content-Length']).to eq((56 + middleware.send(:footer_note).length).to_s)
expect(response).to eq(%w[<html><head></head><body>footer<bullet></bullet></body></html>])
end
it 'should not include the xhr script tag if console_enabled is true' do
expect(Bullet).to receive(:console_enabled?).and_return(true)
_, headers, response = middleware.call({})
expect(headers['Content-Length']).to eq('56')
expect(response).to eq(%w[<html><head></head><body><bullet></bullet></body></html>])
end
it 'should not add the footer-text header for non-html requests when add_footer is true' do
allow(Bullet).to receive(:add_footer).at_least(:once).and_return(true)
app.headers = { 'Content-Type' => 'application/json' }
_, headers, _response = middleware.call({})
expect(headers).not_to include('X-bullet-footer-text')
end
it 'should not add headers for non-html requests when console_enabled is true' do
allow(Bullet).to receive(:console_enabled?).at_least(:once).and_return(true)
app.headers = { 'Content-Type' => 'application/json' }
_, headers, _response = middleware.call({})
expect(headers).not_to include('X-bullet-console-text')
end
end
end
context 'with notifications present' do
before do
expect(Bullet).to receive(:notification?).and_return(true)
end
include_examples 'inject notifiers'
end
context 'with always_append_html_body true' do
before do
expect(Bullet).to receive(:always_append_html_body).and_return(true)
end
include_examples 'inject notifiers'
end
context 'when skip_html_injection is enabled' do
it 'should not try to inject html' do
expected_response = Support::ResponseDouble.new 'Actual body'
app.response = expected_response
allow(Bullet).to receive(:notification?).and_return(true)
allow(Bullet).to receive(:skip_html_injection?).and_return(true)
expect(Bullet).to receive(:gather_inline_notifications).never
expect(middleware).to receive(:xhr_script).never
expect(Bullet).to receive(:perform_out_of_channel_notifications)
_, _, response = middleware.call('Content-Type' => 'text/html')
expect(response).to eq(expected_response)
end
end
end
context 'when Bullet is disabled' do
before(:each) { allow(Bullet).to receive(:enable?).and_return(false) }
it 'should not call Bullet.start_request' do
expect(Bullet).not_to receive(:start_request)
middleware.call({})
end
end
end
context '#set_header' do
it 'should truncate headers to under 8kb' do
long_header = ['a' * 1_024] * 10
expected_res = (['a' * 1_024] * 7).to_json
expect(middleware.set_header({}, 'Dummy-Header', long_header)).to eq(expected_res)
end
end
describe '#response_body' do
let(:response) { double }
let(:body_string) { '<html><body>My Body</body></html>' }
context 'when `response` responds to `body`' do
before { allow(response).to receive(:body).and_return(body) }
context 'when `body` returns an Array' do
let(:body) { [body_string, 'random string'] }
it 'should return the plain body string' do
expect(middleware.response_body(response)).to eq body_string
end
end
context 'when `body` does not return an Array' do
let(:body) { body_string }
it 'should return the plain body string' do
expect(middleware.response_body(response)).to eq body_string
end
end
end
context 'when `response` does not respond to `body`' do
before { allow(response).to receive(:first).and_return(body_string) }
it 'should return the plain body string' do
expect(middleware.response_body(response)).to eq body_string
end
end
begin
require 'rack/files'
context 'when `response` is a Rack::Files::Iterator' do
let(:response) { instance_double(::Rack::Files::Iterator) }
before { allow(response).to receive(:is_a?).with(::Rack::Files::Iterator) { true } }
it 'should return nil' do
expect(middleware.response_body(response)).to be_nil
end
end
rescue LoadError
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/notification_collector_spec.rb | spec/bullet/notification_collector_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
describe NotificationCollector do
subject { NotificationCollector.new.tap { |collector| collector.add('value') } }
context '#add' do
it 'should add a value' do
subject.add('value1')
expect(subject.collection).to be_include('value1')
end
end
context '#reset' do
it 'should reset collector' do
subject.reset
expect(subject.collection).to be_empty
end
end
context '#notifications_present?' do
it 'should be true if collection is not empty' do
expect(subject).to be_notifications_present
end
it 'should be false if collection is empty' do
subject.reset
expect(subject).not_to be_notifications_present
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/detector/counter_cache_spec.rb | spec/bullet/detector/counter_cache_spec.rb | # frozen_string_literal: true
require 'spec_helper'
using Bullet::Ext::Object
module Bullet
module Detector
describe CounterCache do
before :all do
@post1 = Post.first
@post2 = Post.last
end
context '.add_counter_cache' do
it 'should create notification if conditions met' do
expect(CounterCache).to receive(:conditions_met?).with(@post1, %i[comments]).and_return(true)
expect(CounterCache).to receive(:create_notification).with('Post', %i[comments])
CounterCache.add_counter_cache(@post1, %i[comments])
end
it 'should not create notification if conditions not met' do
expect(CounterCache).to receive(:conditions_met?).with(@post1, %i[comments]).and_return(false)
expect(CounterCache).to receive(:create_notification).never
CounterCache.add_counter_cache(@post1, %i[comments])
end
end
context '.add_possible_objects' do
it 'should add possible objects' do
CounterCache.add_possible_objects([@post1, @post2])
expect(CounterCache.possible_objects).to be_include(@post1.bullet_key)
expect(CounterCache.possible_objects).to be_include(@post2.bullet_key)
end
it 'should add impossible object' do
CounterCache.add_impossible_object(@post1)
expect(CounterCache.impossible_objects).to be_include(@post1.bullet_key)
end
end
context '.conditions_met?' do
it 'should be true when object is possible, not impossible' do
CounterCache.add_possible_objects(@post1)
expect(CounterCache.conditions_met?(@post1, :associations)).to eq true
end
it 'should be false when object is not possible' do
expect(CounterCache.conditions_met?(@post1, :associations)).to eq false
end
it 'should be false when object is possible, and impossible' do
CounterCache.add_possible_objects(@post1)
CounterCache.add_impossible_object(@post1)
expect(CounterCache.conditions_met?(@post1, :associations)).to eq false
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/detector/association_spec.rb | spec/bullet/detector/association_spec.rb | # frozen_string_literal: true
require 'spec_helper'
using Bullet::Ext::Object
module Bullet
module Detector
describe Association do
before :all do
@post1 = Post.first
@post2 = Post.last
end
context '.add_object_association' do
it 'should add object, associations pair' do
Association.add_object_associations(@post1, :associations)
expect(Association.send(:object_associations)).to be_include(@post1.bullet_key, :associations)
end
end
context '.add_call_object_associations' do
it 'should add call object, associations pair' do
Association.add_call_object_associations(@post1, :associations)
expect(Association.send(:call_object_associations)).to be_include(@post1.bullet_key, :associations)
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/detector/unused_eager_loading_spec.rb | spec/bullet/detector/unused_eager_loading_spec.rb | # frozen_string_literal: true
require 'spec_helper'
using Bullet::Ext::Object
module Bullet
module Detector
describe UnusedEagerLoading do
before(:all) do
@post = Post.first
@post2 = Post.all[1]
@post3 = Post.last
end
context '.call_associations' do
it 'should get empty array if eager_loadings' do
expect(UnusedEagerLoading.send(:call_associations, @post.bullet_key, Set.new([:association]))).to be_empty
end
it 'should get call associations if object and association are both in eager_loadings and call_object_associations' do
UnusedEagerLoading.add_eager_loadings([@post], :association)
UnusedEagerLoading.add_call_object_associations(@post, :association)
expect(UnusedEagerLoading.send(:call_associations, @post.bullet_key, Set.new([:association]))).to eq(
[:association]
)
end
it 'should not get call associations if not exist in call_object_associations' do
UnusedEagerLoading.add_eager_loadings([@post], :association)
expect(UnusedEagerLoading.send(:call_associations, @post.bullet_key, Set.new([:association]))).to be_empty
end
end
context '.diff_object_associations' do
it 'should return associations not exist in call_association' do
expect(UnusedEagerLoading.send(:diff_object_associations, @post.bullet_key, Set.new([:association]))).to eq(
[:association]
)
end
it 'should return empty if associations exist in call_association' do
UnusedEagerLoading.add_eager_loadings([@post], :association)
UnusedEagerLoading.add_call_object_associations(@post, :association)
expect(
UnusedEagerLoading.send(:diff_object_associations, @post.bullet_key, Set.new([:association]))
).to be_empty
end
end
context '.check_unused_preload_associations' do
let(:paths) { %w[/dir1 /dir1/subdir] }
it 'should create notification if object_association_diff is not empty' do
UnusedEagerLoading.add_object_associations(@post, :association)
allow(UnusedEagerLoading).to receive(:caller_in_project).and_return(paths)
expect(UnusedEagerLoading).to receive(:create_notification).with(paths, 'Post', [:association])
UnusedEagerLoading.check_unused_preload_associations
end
it 'should not create notification if object_association_diff is empty' do
UnusedEagerLoading.add_object_associations(@post, :association)
UnusedEagerLoading.add_eager_loadings([@post], :association)
UnusedEagerLoading.add_call_object_associations(@post, :association)
expect(
UnusedEagerLoading.send(:diff_object_associations, @post.bullet_key, Set.new([:association]))
).to be_empty
expect(UnusedEagerLoading).not_to receive(:create_notification).with('Post', [:association])
UnusedEagerLoading.check_unused_preload_associations
end
it 'should create call stack for notification' do
UnusedEagerLoading.add_object_associations(@post, :association)
expect(UnusedEagerLoading.send(:call_stacks).registry).not_to be_empty
end
end
context '.add_eager_loadings' do
it 'should add objects, associations pair when eager_loadings are empty' do
UnusedEagerLoading.add_eager_loadings([@post, @post2], :associations)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include(
[@post.bullet_key, @post2.bullet_key],
:associations
)
end
it 'should add objects, associations pair for existing eager_loadings' do
UnusedEagerLoading.add_eager_loadings([@post, @post2], :association1)
UnusedEagerLoading.add_eager_loadings([@post, @post2], :association2)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include(
[@post.bullet_key, @post2.bullet_key],
:association1
)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include(
[@post.bullet_key, @post2.bullet_key],
:association2
)
end
it 'should merge objects, associations pair for existing eager_loadings' do
UnusedEagerLoading.add_eager_loadings([@post], :association1)
UnusedEagerLoading.add_eager_loadings([@post, @post2], :association2)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post.bullet_key], :association1)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post.bullet_key], :association2)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post2.bullet_key], :association2)
end
it 'should vmerge objects recursively, associations pair for existing eager_loadings' do
UnusedEagerLoading.add_eager_loadings([@post, @post2], :association1)
UnusedEagerLoading.add_eager_loadings([@post, @post3], :association1)
UnusedEagerLoading.add_eager_loadings([@post, @post3], :association2)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post.bullet_key], :association1)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post.bullet_key], :association2)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post2.bullet_key], :association1)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post3.bullet_key], :association1)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post3.bullet_key], :association2)
end
it 'should delete objects, associations pair for existing eager_loadings' do
UnusedEagerLoading.add_eager_loadings([@post, @post2], :association1)
UnusedEagerLoading.add_eager_loadings([@post], :association2)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post.bullet_key], :association1)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post.bullet_key], :association2)
expect(UnusedEagerLoading.send(:eager_loadings)).to be_include([@post2.bullet_key], :association1)
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/detector/n_plus_one_query_spec.rb | spec/bullet/detector/n_plus_one_query_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'ostruct'
using Bullet::Ext::Object
module Bullet
module Detector
describe NPlusOneQuery do
before(:all) do
@post = Post.first
@post2 = Post.last
end
context '.call_association' do
it 'should add call_object_associations' do
expect(NPlusOneQuery).to receive(:add_call_object_associations).with(@post, :associations)
NPlusOneQuery.call_association(@post, :associations)
end
end
context '.possible?' do
it 'should be true if possible_objects contain' do
NPlusOneQuery.add_possible_objects(@post)
expect(NPlusOneQuery.possible?(@post)).to eq true
end
end
context '.impossible?' do
it 'should be true if impossible_objects contain' do
NPlusOneQuery.add_impossible_object(@post)
expect(NPlusOneQuery.impossible?(@post)).to eq true
end
end
context '.association?' do
it 'should be true if object, associations pair is already existed' do
NPlusOneQuery.add_object_associations(@post, :association)
expect(NPlusOneQuery.association?(@post, :association)).to eq true
end
it 'should be false if object, association pair is not existed' do
NPlusOneQuery.add_object_associations(@post, :association1)
expect(NPlusOneQuery.association?(@post, :association2)).to eq false
end
end
context '.conditions_met?' do
it 'should be true if object is possible, not impossible and object, associations pair is not already existed' do
allow(NPlusOneQuery).to receive(:possible?).with(@post).and_return(true)
allow(NPlusOneQuery).to receive(:impossible?).with(@post).and_return(false)
allow(NPlusOneQuery).to receive(:association?).with(@post, :associations).and_return(false)
expect(NPlusOneQuery.conditions_met?(@post, :associations)).to eq true
end
it 'should be false if object is not possible, not impossible and object, associations pair is not already existed' do
allow(NPlusOneQuery).to receive(:possible?).with(@post).and_return(false)
allow(NPlusOneQuery).to receive(:impossible?).with(@post).and_return(false)
allow(NPlusOneQuery).to receive(:association?).with(@post, :associations).and_return(false)
expect(NPlusOneQuery.conditions_met?(@post, :associations)).to eq false
end
it 'should be false if object is possible, but impossible and object, associations pair is not already existed' do
allow(NPlusOneQuery).to receive(:possible?).with(@post).and_return(true)
allow(NPlusOneQuery).to receive(:impossible?).with(@post).and_return(true)
allow(NPlusOneQuery).to receive(:association?).with(@post, :associations).and_return(false)
expect(NPlusOneQuery.conditions_met?(@post, :associations)).to eq false
end
it 'should be false if object is possible, not impossible and object, associations pair is already existed' do
allow(NPlusOneQuery).to receive(:possible?).with(@post).and_return(true)
allow(NPlusOneQuery).to receive(:impossible?).with(@post).and_return(false)
allow(NPlusOneQuery).to receive(:association?).with(@post, :associations).and_return(true)
expect(NPlusOneQuery.conditions_met?(@post, :associations)).to eq false
end
end
context '.call_association' do
it 'should create notification if conditions met' do
expect(NPlusOneQuery).to receive(:conditions_met?).with(@post, :association).and_return(true)
expect(NPlusOneQuery).to receive(:caller_in_project).and_return(%w[caller])
expect(NPlusOneQuery).to receive(:create_notification).with(%w[caller], 'Post', :association)
NPlusOneQuery.call_association(@post, :association)
end
it 'should not create notification if conditions not met' do
expect(NPlusOneQuery).to receive(:conditions_met?).with(@post, :association).and_return(false)
expect(NPlusOneQuery).not_to receive(:caller_in_project!)
expect(NPlusOneQuery).not_to receive(:create_notification).with('Post', :association)
NPlusOneQuery.call_association(@post, :association)
end
context 'stacktrace_excludes' do
before { Bullet.stacktrace_excludes = [/def/] }
after { Bullet.stacktrace_excludes = nil }
it 'should not create notification when stacktrace contains paths that are in the exclude list' do
in_project = OpenStruct.new(absolute_path: File.join(Dir.pwd, 'abc', 'abc.rb'))
included_path = OpenStruct.new(absolute_path: '/ghi/ghi.rb')
excluded_path = OpenStruct.new(absolute_path: '/def/def.rb')
expect(NPlusOneQuery).to receive(:caller_locations).and_return([in_project, included_path, excluded_path])
expect(NPlusOneQuery).to_not receive(:create_notification)
NPlusOneQuery.call_association(@post, :association)
end
# just a sanity spec to make sure the following spec works correctly
it "should create notification when stacktrace contains methods that aren't in the exclude list" do
method = NPlusOneQuery.method(:excluded_stacktrace_path?).source_location
in_project = OpenStruct.new(absolute_path: File.join(Dir.pwd, 'abc', 'abc.rb'))
excluded_path = OpenStruct.new(absolute_path: method.first, lineno: method.last)
expect(NPlusOneQuery).to receive(:caller_locations).at_least(1).and_return([in_project, excluded_path])
expect(NPlusOneQuery).to receive(:conditions_met?).and_return(true)
expect(NPlusOneQuery).to receive(:create_notification)
NPlusOneQuery.call_association(@post, :association)
end
it 'should not create notification when stacktrace contains methods that are in the exclude list' do
method = NPlusOneQuery.method(:excluded_stacktrace_path?).source_location
Bullet.stacktrace_excludes = [method]
in_project = OpenStruct.new(absolute_path: File.join(Dir.pwd, 'abc', 'abc.rb'))
excluded_path = OpenStruct.new(absolute_path: method.first, lineno: method.last)
expect(NPlusOneQuery).to receive(:caller_locations).and_return([in_project, excluded_path])
expect(NPlusOneQuery).to_not receive(:create_notification)
NPlusOneQuery.call_association(@post, :association)
end
end
end
context '.add_possible_objects' do
it 'should add possible objects' do
NPlusOneQuery.add_possible_objects([@post, @post2])
expect(NPlusOneQuery.possible_objects).to be_include(@post.bullet_key)
expect(NPlusOneQuery.possible_objects).to be_include(@post2.bullet_key)
end
it 'should not raise error if object is nil' do
expect { NPlusOneQuery.add_possible_objects(nil) }
.not_to raise_error
end
end
context '.add_impossible_object' do
it 'should add impossible object' do
NPlusOneQuery.add_impossible_object(@post)
expect(NPlusOneQuery.impossible_objects).to be_include(@post.bullet_key)
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/detector/base_spec.rb | spec/bullet/detector/base_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
module Detector
describe Base do
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/notification/counter_cache_spec.rb | spec/bullet/notification/counter_cache_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
module Notification
describe CounterCache do
subject { CounterCache.new(Post, %i[comments votes]) }
it { expect(subject.body).to eq(' Post => [:comments, :votes]') }
it { expect(subject.title).to eq('Need Counter Cache with Active Record size') }
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/notification/unused_eager_loading_spec.rb | spec/bullet/notification/unused_eager_loading_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
module Notification
describe UnusedEagerLoading do
subject { UnusedEagerLoading.new([''], Post, %i[comments votes], 'path') }
it do
expect(subject.body).to eq(
" Post => [:comments, :votes]\n Remove from your query: .includes([:comments, :votes])"
)
end
it { expect(subject.title).to eq('AVOID eager loading in path') }
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/notification/n_plus_one_query_spec.rb | spec/bullet/notification/n_plus_one_query_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
module Notification
describe NPlusOneQuery do
subject { NPlusOneQuery.new([%w[caller1 caller2]], Post, %i[comments votes], 'path') }
it do
expect(subject.body_with_caller).to eq(
" Post => [:comments, :votes]\n Add to your query: .includes([:comments, :votes])\nCall stack\n caller1\n caller2\n"
)
end
it do
expect([subject.body_with_caller, subject.body_with_caller]).to eq(
[
" Post => [:comments, :votes]\n Add to your query: .includes([:comments, :votes])\nCall stack\n caller1\n caller2\n",
" Post => [:comments, :votes]\n Add to your query: .includes([:comments, :votes])\nCall stack\n caller1\n caller2\n"
]
)
end
it do
expect(subject.body).to eq(" Post => [:comments, :votes]\n Add to your query: .includes([:comments, :votes])")
end
it { expect(subject.title).to eq('USE eager loading in path') }
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/notification/base_spec.rb | spec/bullet/notification/base_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
module Notification
describe Base do
subject { Base.new(Post, %i[comments votes]) }
context '#title' do
it 'should raise NoMethodError' do
expect { subject.title }
.to raise_error(NoMethodError)
end
end
context '#body' do
it 'should raise NoMethodError' do
expect { subject.body }
.to raise_error(NoMethodError)
end
end
context '#whoami' do
it 'should display user name' do
user = `whoami`.chomp
expect(subject.whoami).to eq("user: #{user}")
end
it 'should leverage ENV parameter' do
temp_env_variable('USER', 'bogus') { expect(subject.whoami).to eq('user: bogus') }
end
it 'should return blank if no user available' do
temp_env_variable('USER', '') do
expect(subject).to receive(:`).with('whoami').and_return('')
expect(subject.whoami).to eq('')
end
end
it 'should return blank if whoami is not available' do
temp_env_variable('USER', '') do
expect(subject).to receive(:`).with('whoami').and_raise(Errno::ENOENT)
expect(subject.whoami).to eq('')
end
end
def temp_env_variable(name, value)
old_value = ENV[name]
ENV[name] = value
yield
ensure
ENV[name] = old_value
end
end
context '#body_with_caller' do
it 'should return body' do
allow(subject).to receive(:body).and_return('body')
allow(subject).to receive(:call_stack_messages).and_return('call_stack_messages')
expect(subject.body_with_caller).to eq("body\ncall_stack_messages\n")
end
end
context '#notification_data' do
it 'should return notification data' do
allow(subject).to receive(:whoami).and_return('whoami')
allow(subject).to receive(:url).and_return('url')
allow(subject).to receive(:title).and_return('title')
allow(subject).to receive(:body_with_caller).and_return('body_with_caller')
expect(subject.notification_data).to eq(user: 'whoami', url: 'url', title: 'title', body: 'body_with_caller')
end
context 'when skip_user_in_notification is true' do
before { allow(Bullet).to receive(:skip_user_in_notification).and_return(true) }
it 'should return notification data without user' do
allow(subject).to receive(:url).and_return('url')
allow(subject).to receive(:title).and_return('title')
allow(subject).to receive(:body_with_caller).and_return('body_with_caller')
expect(subject.notification_data).to eq(url: 'url', title: 'title', body: 'body_with_caller')
end
end
end
context '#notify_inline' do
it 'should send full_notice to notifier' do
notifier = double
allow(subject).to receive(:notifier).and_return(notifier)
allow(subject).to receive(:notification_data).and_return({ foo: :bar })
expect(notifier).to receive(:inline_notify).with({ foo: :bar })
subject.notify_inline
end
end
context '#notify_out_of_channel' do
it 'should send full_out_of_channel to notifier' do
notifier = double
allow(subject).to receive(:notifier).and_return(notifier)
allow(subject).to receive(:notification_data).and_return({ foo: :bar })
expect(notifier).to receive(:out_of_channel_notify).with({ foo: :bar })
subject.notify_out_of_channel
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/ext/string_spec.rb | spec/bullet/ext/string_spec.rb | # frozen_string_literal: true
require 'spec_helper'
using Bullet::Ext::String
describe String do
context 'bullet_class_name' do
it 'should only return class name' do
expect('Post:1'.bullet_class_name).to eq('Post')
end
it 'should return class name with namespace' do
expect('Mongoid::Post:1234567890'.bullet_class_name).to eq('Mongoid::Post')
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/ext/object_spec.rb | spec/bullet/ext/object_spec.rb | # frozen_string_literal: true
require 'spec_helper'
using Bullet::Ext::Object
describe Object do
context 'bullet_key' do
it 'should return class and id composition' do
post = Post.first
expect(post.bullet_key).to eq("Post:#{post.id}")
end
if mongoid?
it 'should return class with namespace and id composition' do
post = Mongoid::Post.first
expect(post.bullet_key).to eq("Mongoid::Post:#{post.id}")
end
end
end
context 'bullet_primary_key_value' do
it 'should return id' do
post = Post.first
expect(post.bullet_primary_key_value).to eq(post.id)
end
it 'should return primary key value' do
Post.primary_key = 'name'
post = Post.first
expect(post.bullet_primary_key_value).to eq(post.name)
Post.primary_key = 'id'
end
it 'should return value for multiple primary keys from the composite_primary_key gem' do
allow(Post).to receive(:primary_keys).and_return(%i[category_id writer_id])
post = Post.first
expect(post.bullet_primary_key_value).to eq("#{post.category_id},#{post.writer_id}")
end
it 'should return empty value for multiple primary keys without values' do
allow(Post).to receive(:primary_keys).and_return(%i[category_id writer_id])
post = Post.select('1 as myfield').first
expect(post.bullet_primary_key_value).to eq("")
end
if Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('7.1')
it 'should return value for multiple primary keys from ActiveRecord 7.1' do
allow(Post).to receive(:primary_key).and_return(%i[category_id writer_id])
post = Post.first
expect(post.bullet_primary_key_value).to eq("#{post.category_id},#{post.writer_id}")
end
end
it 'should return nil for unpersisted records' do
post = Post.new(id: 123)
expect(post.bullet_primary_key_value).to be_nil
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/registry/association_spec.rb | spec/bullet/registry/association_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
module Registry
describe Association do
subject { Association.new.tap { |association| association.add(%w[key1 key2], 'value') } }
context '#merge' do
it 'should merge key/value' do
subject.merge('key0', 'value0')
expect(subject['key0']).to be_include('value0')
end
end
context '#similarly_associated' do
it 'should return similarly associated keys' do
expect(subject.similarly_associated('key1', Set.new(%w[value]))).to eq(%w[key1 key2])
end
it 'should return empty if key does not exist' do
expect(subject.similarly_associated('key3', Set.new(%w[value]))).to be_empty
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/registry/object_spec.rb | spec/bullet/registry/object_spec.rb | # frozen_string_literal: true
require 'spec_helper'
using Bullet::Ext::Object
module Bullet
module Registry
describe Object do
let(:post) { Post.first }
let(:another_post) { Post.last }
subject { Object.new.tap { |object| object.add(post.bullet_key) } }
context '#include?' do
it 'should include the object' do
expect(subject).to be_include(post.bullet_key)
end
end
context '#add' do
it 'should add an object' do
subject.add(another_post.bullet_key)
expect(subject).to be_include(another_post.bullet_key)
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/spec/bullet/registry/base_spec.rb | spec/bullet/registry/base_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Bullet
module Registry
describe Base do
subject { Base.new.tap { |base| base.add('key', 'value') } }
context '#[]' do
it 'should get value by key' do
expect(subject['key']).to eq(Set.new(%w[value]))
end
end
context '#delete' do
it 'should delete key' do
subject.delete('key')
expect(subject['key']).to be_nil
end
end
context '#add' do
it 'should add value with string' do
subject.add('key', 'new_value')
expect(subject['key']).to eq(Set.new(%w[value new_value]))
end
it 'should add value with array' do
subject.add('key', %w[value1 value2])
expect(subject['key']).to eq(Set.new(%w[value value1 value2]))
end
end
context '#include?' do
it 'should include key/value' do
expect(subject.include?('key', 'value')).to eq true
end
it 'should not include wrong key/value' do
expect(subject.include?('key', 'val')).to eq false
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet.rb | lib/bullet.rb | # frozen_string_literal: true
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/module/delegation'
require 'set'
require 'uniform_notifier'
require 'bullet/ext/object'
require 'bullet/ext/string'
require 'bullet/dependency'
require 'bullet/stack_trace_filter'
module Bullet
extend Dependency
autoload :ActiveRecord, "bullet/#{active_record_version}" if active_record?
autoload :Mongoid, "bullet/#{mongoid_version}" if mongoid?
autoload :Rack, 'bullet/rack'
autoload :ActiveJob, 'bullet/active_job'
autoload :Notification, 'bullet/notification'
autoload :Detector, 'bullet/detector'
autoload :Registry, 'bullet/registry'
autoload :NotificationCollector, 'bullet/notification_collector'
if defined?(Rails::Railtie)
class BulletRailtie < Rails::Railtie
initializer 'bullet.add_middleware', after: :load_config_initializers do |app|
if defined?(ActionDispatch::ContentSecurityPolicy::Middleware) && Rails.application.config.content_security_policy && !app.config.api_only
app.middleware.insert_before ActionDispatch::ContentSecurityPolicy::Middleware, Bullet::Rack
else
app.middleware.use Bullet::Rack
end
end
end
end
class << self
attr_writer :n_plus_one_query_enable,
:unused_eager_loading_enable,
:counter_cache_enable,
:stacktrace_includes,
:stacktrace_excludes,
:skip_html_injection
attr_reader :safelist
attr_accessor :add_footer,
:orm_patches_applied,
:skip_http_headers,
:always_append_html_body,
:skip_user_in_notification
available_notifiers =
UniformNotifier::AVAILABLE_NOTIFIERS.select { |notifier| notifier != :raise }
.map { |notifier| "#{notifier}=" }
available_notifiers_options = { to: UniformNotifier }
delegate(*available_notifiers, **available_notifiers_options)
def raise=(should_raise)
UniformNotifier.raise = (should_raise ? Notification::UnoptimizedQueryError : false)
end
DETECTORS = [
Bullet::Detector::NPlusOneQuery,
Bullet::Detector::UnusedEagerLoading,
Bullet::Detector::CounterCache
].freeze
def enable=(enable)
@enable = enable
if enable?
reset_safelist
unless orm_patches_applied
self.orm_patches_applied = true
Bullet::Mongoid.enable if mongoid?
Bullet::ActiveRecord.enable if active_record?
end
end
end
alias enabled= enable=
def enable?
!!@enable
end
alias enabled? enable?
# Rails.root might be nil if `railties` is a dependency on a project that does not use Rails
def app_root
@app_root ||= (defined?(::Rails.root) && !::Rails.root.nil? ? Rails.root.to_s : Dir.pwd).to_s
end
def n_plus_one_query_enable?
enable? && (@n_plus_one_query_enable.nil? ? true : @n_plus_one_query_enable)
end
def unused_eager_loading_enable?
enable? && (@unused_eager_loading_enable.nil? ? true : @unused_eager_loading_enable)
end
def counter_cache_enable?
enable? && (@counter_cache_enable.nil? ? true : @counter_cache_enable)
end
def stacktrace_includes
@stacktrace_includes ||= []
end
def stacktrace_excludes
@stacktrace_excludes ||= []
end
def add_safelist(options)
reset_safelist
@safelist[options[:type]][options[:class_name]] ||= []
@safelist[options[:type]][options[:class_name]] << options[:association].to_sym
end
def delete_safelist(options)
reset_safelist
@safelist[options[:type]][options[:class_name]] ||= []
@safelist[options[:type]][options[:class_name]].delete(options[:association].to_sym)
@safelist[options[:type]].delete_if { |_key, val| val.empty? }
end
def get_safelist_associations(type, class_name)
Array.wrap(@safelist[type][class_name])
end
def reset_safelist
@safelist ||= { n_plus_one_query: {}, unused_eager_loading: {}, counter_cache: {} }
end
def clear_safelist
@safelist = nil
end
def bullet_logger=(active)
if active
require 'fileutils'
FileUtils.mkdir_p(app_root + '/log')
bullet_log_file = File.open("#{app_root}/log/bullet.log", 'a+')
bullet_log_file.sync = true
UniformNotifier.customized_logger = bullet_log_file
end
end
def debug(title, message)
puts "[Bullet][#{title}] #{message}" if ENV['BULLET_DEBUG'] == 'true'
end
def start_request
Thread.current.thread_variable_set(:bullet_start, true)
Thread.current.thread_variable_set(:bullet_notification_collector, Bullet::NotificationCollector.new)
Thread.current.thread_variable_set(:bullet_object_associations, Bullet::Registry::Base.new)
Thread.current.thread_variable_set(:bullet_call_object_associations, Bullet::Registry::Base.new)
Thread.current.thread_variable_set(:bullet_possible_objects, Bullet::Registry::Object.new)
Thread.current.thread_variable_set(:bullet_impossible_objects, Bullet::Registry::Object.new)
Thread.current.thread_variable_set(:bullet_inversed_objects, Bullet::Registry::Base.new)
Thread.current.thread_variable_set(:bullet_eager_loadings, Bullet::Registry::Association.new)
Thread.current.thread_variable_set(:bullet_call_stacks, Bullet::Registry::CallStack.new)
unless Thread.current.thread_variable_get(:bullet_counter_possible_objects)
Thread.current.thread_variable_set(:bullet_counter_possible_objects, Bullet::Registry::Object.new)
end
unless Thread.current.thread_variable_get(:bullet_counter_impossible_objects)
Thread.current.thread_variable_set(:bullet_counter_impossible_objects, Bullet::Registry::Object.new)
end
end
def end_request
Thread.current.thread_variable_set(:bullet_start, nil)
Thread.current.thread_variable_set(:bullet_notification_collector, nil)
Thread.current.thread_variable_set(:bullet_object_associations, nil)
Thread.current.thread_variable_set(:bullet_call_object_associations, nil)
Thread.current.thread_variable_set(:bullet_possible_objects, nil)
Thread.current.thread_variable_set(:bullet_impossible_objects, nil)
Thread.current.thread_variable_set(:bullet_inversed_objects, nil)
Thread.current.thread_variable_set(:bullet_eager_loadings, nil)
Thread.current.thread_variable_set(:bullet_counter_possible_objects, nil)
Thread.current.thread_variable_set(:bullet_counter_impossible_objects, nil)
end
def start?
enable? && Thread.current.thread_variable_get(:bullet_start)
end
def notification_collector
Thread.current.thread_variable_get(:bullet_notification_collector)
end
def notification?
return unless start?
Bullet::Detector::UnusedEagerLoading.check_unused_preload_associations
notification_collector.notifications_present?
end
def gather_inline_notifications
responses = []
for_each_active_notifier_with_notification { |notification| responses << notification.notify_inline }
responses.join("\n")
end
def perform_out_of_channel_notifications(env = {})
request_uri = build_request_uri(env)
for_each_active_notifier_with_notification do |notification|
notification.url = request_uri
notification.notify_out_of_channel
end
end
def footer_info
info = []
notification_collector.collection.each { |notification| info << notification.short_notice }
info
end
def text_notifications
info = []
notification_collector.collection.each do |notification|
info << notification.notification_data.values.compact.join("\n")
end
info
end
def warnings
notification_collector.collection.each_with_object({}) do |notification, warnings|
warning_type = notification.class.to_s.split(':').last.tableize
warnings[warning_type] ||= []
warnings[warning_type] << notification
end
end
def profile
return_value = nil
if Bullet.enable?
begin
Bullet.start_request
return_value = yield
Bullet.perform_out_of_channel_notifications if Bullet.notification?
ensure
Bullet.end_request
end
else
return_value = yield
end
return_value
end
def console_enabled?
UniformNotifier.active_notifiers.include?(UniformNotifier::JavascriptConsole)
end
def inject_into_page?
return false if defined?(@skip_html_injection) && @skip_html_injection
console_enabled? || add_footer
end
private
def for_each_active_notifier_with_notification
UniformNotifier.active_notifiers.each do |notifier|
notification_collector.collection.each do |notification|
notification.notifier = notifier
yield notification
end
end
end
def build_request_uri(env)
return "#{env['REQUEST_METHOD']} #{env['REQUEST_URI']}" if env['REQUEST_URI']
if env['QUERY_STRING'].present?
"#{env['REQUEST_METHOD']} #{env['PATH_INFO']}?#{env['QUERY_STRING']}"
else
"#{env['REQUEST_METHOD']} #{env['PATH_INFO']}"
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/generators/bullet/install_generator.rb | lib/generators/bullet/install_generator.rb | # frozen_string_literal: true
module Bullet
module Generators
class InstallGenerator < ::Rails::Generators::Base
desc <<~DESC
Description:
Enable bullet in development/test for your application.
DESC
def enable_in_development
environment(nil, env: 'development') do
<<~FILE
config.after_initialize do
Bullet.enable = true
Bullet.alert = true
Bullet.bullet_logger = true
Bullet.console = true
Bullet.rails_logger = true
Bullet.add_footer = true
end
FILE
end
say 'Enabled bullet in config/environments/development.rb'
end
def enable_in_test
return unless yes?('Would you like to enable bullet in test environment? (y/n)')
environment(nil, env: 'test') do
<<~FILE
config.after_initialize do
Bullet.enable = true
Bullet.bullet_logger = true
Bullet.raise = true # raise an error if n+1 query occurs
end
FILE
end
say 'Enabled bullet in config/environments/test.rb'
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/mongoid7x.rb | lib/bullet/mongoid7x.rb | # frozen_string_literal: true
module Bullet
module Mongoid
def self.enable
require 'mongoid'
require 'rubygems'
::Mongoid::Contextual::Mongo.class_eval do
alias_method :origin_first, :first
alias_method :origin_last, :last
alias_method :origin_each, :each
alias_method :origin_eager_load, :eager_load
%i[first last].each do |context|
default = Gem::Version.new(::Mongoid::VERSION) >= Gem::Version.new('7.5') ? nil : {}
define_method(context) do |opts = default|
result = send(:"origin_#{context}", opts)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
end
def each(&block)
return to_enum unless block_given?
first_document = nil
document_count = 0
origin_each do |document|
document_count += 1
if document_count == 1
first_document = document
elsif document_count == 2
Bullet::Detector::NPlusOneQuery.add_possible_objects([first_document, document])
yield(first_document)
first_document = nil
yield(document)
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(document)
yield(document)
end
end
if document_count == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(first_document)
yield(first_document)
end
self
end
def eager_load(docs)
associations = criteria.inclusions.map(&:name)
docs.each { |doc| Bullet::Detector::NPlusOneQuery.add_object_associations(doc, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(docs, associations)
origin_eager_load(docs)
end
end
::Mongoid::Association::Accessors.class_eval do
alias_method :origin_get_relation, :get_relation
private
def get_relation(name, association, object, reload = false)
result = origin_get_relation(name, association, object, reload)
Bullet::Detector::NPlusOneQuery.call_association(self, name) unless association.embedded?
result
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_job.rb | lib/bullet/active_job.rb | # frozen_string_literal: true
module Bullet
module ActiveJob
def self.included(base)
base.class_eval do
around_perform do |_job, block|
Bullet.profile { block.call }
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/mongoid8x.rb | lib/bullet/mongoid8x.rb | module Bullet
module Mongoid
def self.enable
require 'mongoid'
::Mongoid::Contextual::Mongo.class_eval do
alias_method :origin_first, :first
alias_method :origin_last, :last
alias_method :origin_each, :each
alias_method :origin_eager_load, :eager_load
def first(limit = nil)
result = origin_first(limit)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
def last(limit = nil)
result = origin_last(limit)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
def each(&block)
return to_enum unless block_given?
records = []
origin_each { |record| records << record }
if records.length > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
end
records.each(&block)
end
def eager_load(docs)
associations = criteria.inclusions.map(&:name)
docs.each do |doc|
Bullet::Detector::NPlusOneQuery.add_object_associations(doc, associations)
end
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(docs, associations)
origin_eager_load(docs)
end
end
::Mongoid::Association::Accessors.class_eval do
alias_method :origin_get_relation, :get_relation
private
def get_relation(name, association, object, reload = false)
result = origin_get_relation(name, association, object, reload)
unless association.embedded?
Bullet::Detector::NPlusOneQuery.call_association(self, name)
end
result
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/version.rb | lib/bullet/version.rb | # frozen_string_literal: true
module Bullet
VERSION = '8.1.0'
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record72.rb | lib/bullet/active_record72.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, allow_retry: false, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader::Batch.prepend(
Module.new do
def call
if Bullet.start?
@preloaders.each do |preloader|
preloader.records.each { |record|
Bullet::Detector::Association.add_object_associations(record, preloader.associations)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(preloader.records, preloader.associations)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::Branch.prepend(
Module.new do
def preloaders_for_reflection(reflection, reflection_records)
if Bullet.start?
reflection_records.compact!
if reflection_records.first.class.name !~ /^HABTM_/
reflection_records.each { |record|
Bullet::Detector::Association.add_object_associations(record, reflection.name)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(reflection_records, reflection.name)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::ThroughAssociation.prepend(
Module.new do
def source_preloaders
if Bullet.start? && !defined?(@source_preloaders)
preloaders = super
preloaders.each do |preloader|
reflection_name = preloader.send(:reflection).name
preloader.send(:owners).each do |owner|
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection_name)
end
end
else
super
end
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
def instantiate(result_set, strict_loading_value, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
def construct(ar_parent, parent, row, seen, model_cache, strict_loading_value)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id, strict_loading_value)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::Association.prepend(
Module.new do
def inversed_from(record)
if Bullet.start?
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
def inversed_from_queries(record)
if Bullet.start? && inversable?(record)
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
association = owner.association(reflection.through_reflection.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def reader
result = super
if Bullet.start?
if owner.class.name !~ /^HABTM_/
if is_a? ::ActiveRecord::Associations::ThroughAssociation
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
association = owner.association(reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/mongoid4x.rb | lib/bullet/mongoid4x.rb | # frozen_string_literal: true
module Bullet
module Mongoid
def self.enable
require 'mongoid'
::Mongoid::Contextual::Mongo.class_eval do
alias_method :origin_first, :first
alias_method :origin_last, :last
alias_method :origin_each, :each
alias_method :origin_eager_load, :eager_load
def first
result = origin_first
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
def last
result = origin_last
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
def each(&block)
return to_enum unless block
records = []
origin_each { |record| records << record }
if records.length > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
end
records.each(&block)
end
def eager_load(docs)
associations = criteria.inclusions.map(&:name)
docs.each { |doc| Bullet::Detector::NPlusOneQuery.add_object_associations(doc, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(docs, associations)
origin_eager_load(docs)
end
end
::Mongoid::Relations::Accessors.class_eval do
alias_method :origin_get_relation, :get_relation
private
def get_relation(name, metadata, object, reload = false)
result = origin_get_relation(name, metadata, object, reload)
Bullet::Detector::NPlusOneQuery.call_association(self, name) if metadata.macro !~ /embed/
result
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record81.rb | lib/bullet/active_record81.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, allow_retry: false, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader::Batch.prepend(
Module.new do
def call
if Bullet.start?
@preloaders.each do |preloader|
preloader.records.each { |record|
Bullet::Detector::Association.add_object_associations(record, preloader.associations)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(preloader.records, preloader.associations)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::Branch.prepend(
Module.new do
def preloaders_for_reflection(reflection, reflection_records)
if Bullet.start?
reflection_records.compact!
if reflection_records.first.class.name !~ /^HABTM_/
reflection_records.each { |record|
Bullet::Detector::Association.add_object_associations(record, reflection.name)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(reflection_records, reflection.name)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::ThroughAssociation.prepend(
Module.new do
def source_preloaders
if Bullet.start? && !defined?(@source_preloaders)
preloaders = super
preloaders.each do |preloader|
reflection_name = preloader.send(:reflection).name
preloader.send(:owners).each do |owner|
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection_name)
end
end
else
super
end
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
def instantiate(result_set, strict_loading_value, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
def construct(ar_parent, parent, row, seen, model_cache, strict_loading_value)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id, strict_loading_value)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::Association.prepend(
Module.new do
def inversed_from(record)
if Bullet.start?
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
def inversed_from_queries(record)
if Bullet.start? && inversable?(record)
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
association = owner.association(reflection.through_reflection.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def reader
result = super
if Bullet.start?
if owner.class.name !~ /^HABTM_/
if is_a? ::ActiveRecord::Associations::ThroughAssociation
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
association = owner.association(reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record70.rb | lib/bullet/active_record70.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader::Batch.prepend(
Module.new do
def call
if Bullet.start?
@preloaders.each do |preloader|
preloader.records.each { |record|
Bullet::Detector::Association.add_object_associations(record, preloader.associations)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(preloader.records, preloader.associations)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::Branch.prepend(
Module.new do
def preloaders_for_reflection(reflection, reflection_records)
if Bullet.start?
reflection_records.compact!
if reflection_records.first.class.name !~ /^HABTM_/
reflection_records.each { |record|
Bullet::Detector::Association.add_object_associations(record, reflection.name)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(reflection_records, reflection.name)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::ThroughAssociation.prepend(
Module.new do
def source_preloaders
if Bullet.start? && !defined?(@source_preloaders)
preloaders = super
preloaders.each do |preloader|
reflection_name = preloader.send(:reflection).name
preloader.send(:owners).each do |owner|
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection_name)
end
end
else
super
end
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
def instantiate(result_set, strict_loading_value, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
def construct(ar_parent, parent, row, seen, model_cache, strict_loading_value)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id, strict_loading_value)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::Association.prepend(
Module.new do
def inversed_from(record)
if Bullet.start?
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
def inversed_from_queries(record)
if Bullet.start? && inversable?(record)
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
association = owner.association(reflection.through_reflection.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def reader
result = super
if Bullet.start?
if owner.class.name !~ /^HABTM_/
if is_a? ::ActiveRecord::Associations::ThroughAssociation
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
association = owner.association(reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record80.rb | lib/bullet/active_record80.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, allow_retry: false, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader::Batch.prepend(
Module.new do
def call
if Bullet.start?
@preloaders.each do |preloader|
preloader.records.each { |record|
Bullet::Detector::Association.add_object_associations(record, preloader.associations)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(preloader.records, preloader.associations)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::Branch.prepend(
Module.new do
def preloaders_for_reflection(reflection, reflection_records)
if Bullet.start?
reflection_records.compact!
if reflection_records.first.class.name !~ /^HABTM_/
reflection_records.each { |record|
Bullet::Detector::Association.add_object_associations(record, reflection.name)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(reflection_records, reflection.name)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::ThroughAssociation.prepend(
Module.new do
def source_preloaders
if Bullet.start? && !defined?(@source_preloaders)
preloaders = super
preloaders.each do |preloader|
reflection_name = preloader.send(:reflection).name
preloader.send(:owners).each do |owner|
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection_name)
end
end
else
super
end
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
def instantiate(result_set, strict_loading_value, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
def construct(ar_parent, parent, row, seen, model_cache, strict_loading_value)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id, strict_loading_value)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::Association.prepend(
Module.new do
def inversed_from(record)
if Bullet.start?
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
def inversed_from_queries(record)
if Bullet.start? && inversable?(record)
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
association = owner.association(reflection.through_reflection.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def reader
result = super
if Bullet.start?
if owner.class.name !~ /^HABTM_/
if is_a? ::ActiveRecord::Associations::ThroughAssociation
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
association = owner.association(reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/mongoid5x.rb | lib/bullet/mongoid5x.rb | # frozen_string_literal: true
module Bullet
module Mongoid
def self.enable
require 'mongoid'
::Mongoid::Contextual::Mongo.class_eval do
alias_method :origin_first, :first
alias_method :origin_last, :last
alias_method :origin_each, :each
alias_method :origin_eager_load, :eager_load
def first
result = origin_first
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
def last
result = origin_last
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
def each(&block)
return to_enum unless block
records = []
origin_each { |record| records << record }
if records.length > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
end
records.each(&block)
end
def eager_load(docs)
associations = criteria.inclusions.map(&:name)
docs.each { |doc| Bullet::Detector::NPlusOneQuery.add_object_associations(doc, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(docs, associations)
origin_eager_load(docs)
end
end
::Mongoid::Relations::Accessors.class_eval do
alias_method :origin_get_relation, :get_relation
private
def get_relation(name, metadata, object, reload = false)
result = origin_get_relation(name, metadata, object, reload)
Bullet::Detector::NPlusOneQuery.call_association(self, name) if metadata.macro !~ /embed/
result
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/notification_collector.rb | lib/bullet/notification_collector.rb | # frozen_string_literal: true
require 'set'
module Bullet
class NotificationCollector
attr_reader :collection
def initialize
reset
end
def reset
@collection = Set.new
end
def add(value)
@collection << value
end
def notifications_present?
!@collection.empty?
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record61.rb | lib/bullet/active_record61.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader.prepend(
Module.new do
def preloaders_for_one(association, records, scope, polymorphic_parent)
if Bullet.start?
records.compact!
if records.first.class.name !~ /^HABTM_/
records.each { |record| Bullet::Detector::Association.add_object_associations(record, association) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, association)
end
end
super
end
def preloaders_for_reflection(reflection, records, scope)
if Bullet.start?
records.compact!
if records.first.class.name !~ /^HABTM_/
records.each { |record| Bullet::Detector::Association.add_object_associations(record, reflection.name) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, reflection.name)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::ThroughAssociation.prepend(
Module.new do
def preloaded_records
if Bullet.start? && !defined?(@preloaded_records)
source_preloaders.each do |source_preloader|
reflection_name = source_preloader.send(:reflection).name
source_preloader.send(:owners).each do |owner|
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection_name)
end
end
end
super
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
def instantiate(result_set, strict_loading_value, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
def construct(ar_parent, parent, row, seen, model_cache, strict_loading_value)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id, strict_loading_value)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::Association.prepend(
Module.new do
def inversed_from(record)
if Bullet.start?
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
association = owner.association(reflection.through_reflection.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) unless @inversed
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def target
result = super()
if Bullet.start?
if owner.class.name !~ /^HABTM_/ && !@inversed
if is_a? ::ActiveRecord::Associations::ThroughAssociation
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
association = owner.association(reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record52.rb | lib/bullet/active_record52.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader.prepend(
Module.new do
def preloaders_for_one(association, records, scope)
if Bullet.start?
records.compact!
if records.first.class.name !~ /^HABTM_/
records.each { |record| Bullet::Detector::Association.add_object_associations(record, association) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, association)
end
end
super
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
def instantiate(result_set, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id, aliases)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::Association.prepend(
Module.new do
def inversed_from(record)
if Bullet.start?
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
association = owner.association(reflection.through_reflection.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) unless @inversed
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def target
result = super()
if Bullet.start?
if owner.class.name !~ /^HABTM_/ && !@inversed
if is_a? ::ActiveRecord::Associations::ThroughAssociation
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
association = owner.association reflection.through_reflection.name
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/registry.rb | lib/bullet/registry.rb | # frozen_string_literal: true
module Bullet
module Registry
autoload :Base, 'bullet/registry/base'
autoload :Object, 'bullet/registry/object'
autoload :Association, 'bullet/registry/association'
autoload :CallStack, 'bullet/registry/call_stack'
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/rack.rb | lib/bullet/rack.rb | # frozen_string_literal: true
require 'rack/request'
require 'json'
require 'cgi'
module Bullet
class Rack
include Dependency
NONCE_MATCHER = /(script|style)-src .*'nonce-(?<nonce>[A-Za-z0-9+\/]+={0,2})'/
def initialize(app)
@app = app
end
def call(env)
return @app.call(env) unless Bullet.enable?
Bullet.start_request
status, headers, response = @app.call(env)
response_body = nil
if Bullet.notification? || Bullet.always_append_html_body
request = ::Rack::Request.new(env)
if Bullet.inject_into_page? && !skip_html_injection?(request) && !file?(headers) && !sse?(headers) && !empty?(response) && status == 200
if html_request?(headers, response)
response_body = response_body(response)
with_security_policy_nonce(headers) do |nonce|
response_body = append_to_html_body(response_body, footer_note(nonce)) if Bullet.add_footer
response_body = append_to_html_body(response_body, Bullet.gather_inline_notifications)
if Bullet.add_footer && !Bullet.skip_http_headers
response_body = append_to_html_body(response_body, xhr_script(nonce))
end
end
headers['Content-Length'] = response_body.bytesize.to_s
elsif !Bullet.skip_http_headers
set_header(headers, 'X-bullet-footer-text', Bullet.footer_info.uniq) if Bullet.add_footer
set_header(headers, 'X-bullet-console-text', Bullet.text_notifications) if Bullet.console_enabled?
end
end
Bullet.perform_out_of_channel_notifications(env)
end
[status, headers, response_body ? [response_body] : response]
ensure
Bullet.end_request
end
# fix issue if response's body is a Proc
def empty?(response)
# response may be ["Not Found"], ["Move Permanently"], etc, but
# those should not happen if the status is 200
return true if !response.respond_to?(:body) && !response.respond_to?(:first)
body = response_body(response)
body.nil? || body.empty?
end
def append_to_html_body(response_body, content)
body = response_body.dup
content = content.html_safe if content.respond_to?(:html_safe)
if body.include?('</body>')
position = body.rindex('</body>')
body.insert(position, content)
else
body << content
end
end
def footer_note(nonce = nil)
%(<details id="bullet-footer" data-is-bullet-footer><summary>Bullet Warnings</summary><div>#{Bullet.footer_info.uniq.join('<br>')}#{footer_console_message(nonce)}</div>#{footer_style(nonce)}</details>)
end
# Make footer styles work with ContentSecurityPolicy style-src as self
def footer_style(nonce = nil)
css = <<~CSS
details#bullet-footer {cursor: pointer; position: fixed; left: 0px; bottom: 0px; z-index: 9999; background: #fdf2f2; color: #9b1c1c; font-size: 12px; border-radius: 0px 8px 0px 0px; border: 1px solid #9b1c1c;}
details#bullet-footer summary {font-weight: 600; padding: 2px 8px;}
details#bullet-footer div {padding: 8px; border-top: 1px solid #9b1c1c;}
CSS
if nonce
%(<style type="text/css" nonce="#{nonce}">#{css}</style>)
else
%(<style type="text/css">#{css}</style>)
end
end
def set_header(headers, header_name, header_array)
# Many proxy applications such as Nginx and AWS ELB limit
# the size a header to 8KB, so truncate the list of reports to
# be under that limit
header_array.pop while JSON.generate(header_array).length > 8 * 1024
headers[header_name] = JSON.generate(header_array)
end
def skip_html_injection?(request)
query_string = request.env['QUERY_STRING']
return false if query_string.nil? || query_string.empty?
params = simple_parse_query_string(query_string)
params['skip_html_injection'] == 'true'
end
# Simple query string parser
def simple_parse_query_string(query_string)
params = {}
query_string.split('&').each do |pair|
key, value = pair.split('=', 2).map { |s| CGI.unescape(s) }
params[key] = value if key && !key.empty?
end
params
end
def file?(headers)
headers['Content-Transfer-Encoding'] == 'binary' || headers['Content-Disposition']
end
def sse?(headers)
headers['Content-Type'] == 'text/event-stream'
end
def html_request?(headers, response)
headers['Content-Type']&.include?('text/html')
end
def response_body(response)
if response.respond_to?(:body)
Array === response.body ? response.body.first : response.body
elsif response.respond_to?(:first)
response.first
end
end
private
def footer_console_message(nonce = nil)
if Bullet.console_enabled?
footer = %(<br/><span id="console-message">See 'Uniform Notifier' in JS Console for Stacktrace</span>)
css = "details#bullet-footer #console-message {font-style: italic;}"
style =
if nonce
%(<style type="text/css" nonce="#{nonce}">#{css}</style>)
else
%(<style type="text/css">#{css}</style>)
end
footer + style
end
end
# Make footer work for XHR requests by appending data to the footer
def xhr_script(nonce = nil)
script = File.read("#{__dir__}/bullet_xhr.js")
if nonce
"<script type='text/javascript' nonce='#{nonce}'>#{script}</script>"
else
"<script type='text/javascript'>#{script}</script>"
end
end
def with_security_policy_nonce(headers)
csp = headers['Content-Security-Policy'] || headers['Content-Security-Policy-Report-Only'] || ''
matched = csp.match(NONCE_MATCHER)
nonce = matched[:nonce] if matched
if nonce
console_enabled = UniformNotifier.console
alert_enabled = UniformNotifier.alert
UniformNotifier.console = { attributes: { nonce: nonce } } if console_enabled
UniformNotifier.alert = { attributes: { nonce: nonce } } if alert_enabled
yield nonce
UniformNotifier.console = console_enabled
UniformNotifier.alert = alert_enabled
else
yield
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record71.rb | lib/bullet/active_record71.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader::Batch.prepend(
Module.new do
def call
if Bullet.start?
@preloaders.each do |preloader|
preloader.records.each { |record|
Bullet::Detector::Association.add_object_associations(record, preloader.associations)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(preloader.records, preloader.associations)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::Branch.prepend(
Module.new do
def preloaders_for_reflection(reflection, reflection_records)
if Bullet.start?
reflection_records.compact!
if reflection_records.first.class.name !~ /^HABTM_/
reflection_records.each { |record|
Bullet::Detector::Association.add_object_associations(record, reflection.name)
}
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(reflection_records, reflection.name)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::ThroughAssociation.prepend(
Module.new do
def source_preloaders
if Bullet.start? && !defined?(@source_preloaders)
preloaders = super
preloaders.each do |preloader|
reflection_name = preloader.send(:reflection).name
preloader.send(:owners).each do |owner|
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection_name)
end
end
else
super
end
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
def instantiate(result_set, strict_loading_value, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
def construct(ar_parent, parent, row, seen, model_cache, strict_loading_value)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id, strict_loading_value)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::Association.prepend(
Module.new do
def inversed_from(record)
if Bullet.start?
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
def inversed_from_queries(record)
if Bullet.start? && inversable?(record)
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
association = owner.association(reflection.through_reflection.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def reader
result = super
if Bullet.start?
if owner.class.name !~ /^HABTM_/
if is_a? ::ActiveRecord::Associations::ThroughAssociation
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
association = owner.association(reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record41.rb | lib/bullet/active_record41.rb | # frozen_string_literal: true
module Bullet
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.class_eval do
class << self
alias_method :origin_find_by_sql, :find_by_sql
def find_by_sql(sql, binds = [])
result = origin_find_by_sql(sql, binds)
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
end
::ActiveRecord::Relation.class_eval do
alias_method :origin_to_a, :to_a
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def to_a
records = origin_to_a
if Bullet.start?
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
end
::ActiveRecord::Persistence.class_eval do
def _create_record_with_bullet(*args)
_create_record_without_bullet(*args).tap do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
end
end
alias_method_chain :_create_record, :bullet
end
::ActiveRecord::Associations::Preloader.class_eval do
alias_method :origin_preloaders_on, :preloaders_on
def preloaders_on(association, records, scope)
if Bullet.start?
records.compact!
if records.first.class.name !~ /^HABTM_/
records.each { |record| Bullet::Detector::Association.add_object_associations(record, association) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, association)
end
end
origin_preloaders_on(association, records, scope)
end
end
::ActiveRecord::FinderMethods.class_eval do
# add includes in scope
alias_method :origin_find_with_associations, :find_with_associations
def find_with_associations
return origin_find_with_associations { |r| yield r } if block_given?
records = origin_find_with_associations
if Bullet.start?
associations = (eager_load_values + includes_values).uniq
records.each { |record| Bullet::Detector::Association.add_object_associations(record, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, associations)
end
records
end
end
::ActiveRecord::Associations::JoinDependency.class_eval do
alias_method :origin_instantiate, :instantiate
alias_method :origin_construct_model, :construct_model
def instantiate(result_set, aliases)
@bullet_eager_loadings = {}
records = origin_instantiate(result_set, aliases)
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(objects, eager_loadings_hash[objects.first].to_a)
end
end
records
end
# call join associations
def construct_model(record, node, row, model_cache, id, aliases)
result = origin_construct_model(record, node, row, model_cache, id, aliases)
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.nested?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
::ActiveRecord::Associations::CollectionAssociation.class_eval do
# call one to many associations
alias_method :origin_load_target, :load_target
def load_target
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) if Bullet.start? && !@inversed
origin_load_target
end
alias_method :origin_empty?, :empty?
def empty?
if Bullet.start? && !has_cached_counter?(@reflection)
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name)
end
origin_empty?
end
alias_method :origin_include?, :include?
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) if Bullet.start?
origin_include?(object)
end
end
::ActiveRecord::Associations::SingularAssociation.class_eval do
# call has_one and belongs_to associations
alias_method :origin_reader, :reader
def reader(force_reload = false)
result = origin_reader(force_reload)
if Bullet.start?
if @owner.class.name !~ /^HABTM_/ && !@inversed
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name)
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
end
end
result
end
end
::ActiveRecord::Associations::HasManyAssociation.class_eval do
alias_method :origin_count_records, :count_records
def count_records
result = has_cached_counter?
Bullet::Detector::CounterCache.add_counter_cache(@owner, @reflection.name) if Bullet.start? && !result
origin_count_records
end
end
::ActiveRecord::Associations::CollectionProxy.class_eval do
def count(column_name = nil, options = {})
if Bullet.start?
Bullet::Detector::CounterCache.add_counter_cache(proxy_association.owner, proxy_association.reflection.name)
Bullet::Detector::NPlusOneQuery.call_association(proxy_association.owner, proxy_association.reflection.name)
end
super(column_name, options)
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record4.rb | lib/bullet/active_record4.rb | # frozen_string_literal: true
module Bullet
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.class_eval do
class << self
alias_method :origin_find_by_sql, :find_by_sql
def find_by_sql(sql, binds = [])
result = origin_find_by_sql(sql, binds)
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
end
::ActiveRecord::Relation.class_eval do
alias_method :origin_to_a, :to_a
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def to_a
records = origin_to_a
if Bullet.start?
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
records
end
end
::ActiveRecord::Persistence.class_eval do
def _create_record_with_bullet(*args)
_create_record_without_bullet(*args).tap do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
end
end
alias_method_chain :_create_record, :bullet
end
::ActiveRecord::Associations::Preloader.class_eval do
# include query for one to many associations.
# keep this eager loadings.
alias_method :origin_initialize, :initialize
def initialize(records, associations, preload_scope = nil)
origin_initialize(records, associations, preload_scope)
if Bullet.start?
records = [records].flatten.compact.uniq
return if records.empty?
records.each { |record| Bullet::Detector::Association.add_object_associations(record, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, associations)
end
end
end
::ActiveRecord::FinderMethods.class_eval do
# add includes in scope
alias_method :origin_find_with_associations, :find_with_associations
def find_with_associations
records = origin_find_with_associations
if Bullet.start?
associations = (eager_load_values + includes_values).uniq
records.each { |record| Bullet::Detector::Association.add_object_associations(record, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, associations)
end
records
end
end
::ActiveRecord::Associations::JoinDependency.class_eval do
alias_method :origin_instantiate, :instantiate
alias_method :origin_construct_association, :construct_association
def instantiate(rows)
@bullet_eager_loadings = {}
records = origin_instantiate(rows)
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(objects, eager_loadings_hash[objects.first].to_a)
end
end
records
end
# call join associations
def construct_association(record, join, row)
result = origin_construct_association(record, join, row)
if Bullet.start?
associations = [join.reflection.name]
if join.reflection.nested?
associations << join.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
::ActiveRecord::Associations::CollectionAssociation.class_eval do
# call one to many associations
alias_method :origin_load_target, :load_target
def load_target
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) if Bullet.start?
origin_load_target
end
alias_method :origin_include?, :include?
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) if Bullet.start?
origin_include?(object)
end
end
::ActiveRecord::Associations::HasManyAssociation.class_eval do
alias_method :origin_empty?, :empty?
def empty?
if Bullet.start? && !loaded? && !has_cached_counter?(@reflection)
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name)
end
origin_empty?
end
end
::ActiveRecord::Associations::HasAndBelongsToManyAssociation.class_eval do
alias_method :origin_empty?, :empty?
def empty?
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) if Bullet.start? && !loaded?
origin_empty?
end
end
::ActiveRecord::Associations::SingularAssociation.class_eval do
# call has_one and belongs_to associations
alias_method :origin_reader, :reader
def reader(force_reload = false)
result = origin_reader(force_reload)
if Bullet.start?
unless @inversed
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name)
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
end
end
result
end
end
::ActiveRecord::Associations::HasManyAssociation.class_eval do
alias_method :origin_has_cached_counter?, :has_cached_counter?
def has_cached_counter?(reflection = reflection())
result = origin_has_cached_counter?(reflection)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name) if Bullet.start? && !result
result
end
end
::ActiveRecord::Associations::CollectionProxy.class_eval do
def count(column_name = nil, options = {})
if Bullet.start?
Bullet::Detector::CounterCache.add_counter_cache(proxy_association.owner, proxy_association.reflection.name)
Bullet::Detector::NPlusOneQuery.call_association(proxy_association.owner, proxy_association.reflection.name)
end
super(column_name, options)
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/stack_trace_filter.rb | lib/bullet/stack_trace_filter.rb | # frozen_string_literal: true
require "bundler"
using Bullet::Ext::Object
module Bullet
module StackTraceFilter
VENDOR_PATH = '/vendor'
# @param bullet_key[String] - use this to get stored call stack from call_stacks object.
def caller_in_project(bullet_key = nil)
vendor_root = Bullet.app_root + VENDOR_PATH
bundler_path = Bundler.bundle_path.to_s
select_caller_locations(bullet_key) do |location|
caller_path = location_as_path(location)
caller_path.include?(Bullet.app_root) && !caller_path.include?(vendor_root) &&
!caller_path.include?(bundler_path) || Bullet.stacktrace_includes.any? { |include_pattern|
pattern_matches?(location, include_pattern)
}
end
end
def excluded_stacktrace_path?
Bullet.stacktrace_excludes.any? do |exclude_pattern|
caller_in_project.any? { |location| pattern_matches?(location, exclude_pattern) }
end
end
private
def pattern_matches?(location, pattern)
path = location_as_path(location)
case pattern
when Array
pattern_path = pattern.first
filter = pattern.last
return false unless pattern_matches?(location, pattern_path)
case filter
when Range
filter.include?(location.lineno)
when Integer
filter == location.lineno
when String
filter == location.base_label
end
when String
path.include?(pattern)
when Regexp
path =~ pattern
end
end
def location_as_path(location)
return location if location.is_a?(String)
location.absolute_path.to_s
end
def select_caller_locations(bullet_key = nil)
call_stack = bullet_key ? call_stacks[bullet_key] : caller_locations
call_stack.select { |location| yield location }
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/mongoid6x.rb | lib/bullet/mongoid6x.rb | # frozen_string_literal: true
module Bullet
module Mongoid
def self.enable
require 'mongoid'
::Mongoid::Contextual::Mongo.class_eval do
alias_method :origin_first, :first
alias_method :origin_last, :last
alias_method :origin_each, :each
alias_method :origin_eager_load, :eager_load
def first(opt = {})
result = origin_first(opt)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
def last(opt = {})
result = origin_last(opt)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
def each(&block)
return to_enum unless block
records = []
origin_each { |record| records << record }
if records.length > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
end
records.each(&block)
end
def eager_load(docs)
associations = criteria.inclusions.map(&:name)
docs.each { |doc| Bullet::Detector::NPlusOneQuery.add_object_associations(doc, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(docs, associations)
origin_eager_load(docs)
end
end
::Mongoid::Relations::Accessors.class_eval do
alias_method :origin_get_relation, :get_relation
private
def get_relation(name, metadata, object, reload = false)
result = origin_get_relation(name, metadata, object, reload)
Bullet::Detector::NPlusOneQuery.call_association(self, name) if metadata.macro !~ /embed/
result
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record60.rb | lib/bullet/active_record60.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader.prepend(
Module.new do
def preloaders_for_one(association, records, scope, polymorphic_parent)
if Bullet.start?
records.compact!
if records.first.class.name !~ /^HABTM_/
records.each { |record| Bullet::Detector::Association.add_object_associations(record, association) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, association)
end
end
super
end
def preloaders_for_reflection(reflection, records, scope)
if Bullet.start?
records.compact!
if records.first.class.name !~ /^HABTM_/
records.each { |record| Bullet::Detector::Association.add_object_associations(record, reflection.name) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, reflection.name)
end
end
super
end
end
)
::ActiveRecord::Associations::Preloader::ThroughAssociation.prepend(
Module.new do
def preloaded_records
if Bullet.start? && !defined?(@preloaded_records)
source_preloaders.each do |source_preloader|
reflection_name = source_preloader.send(:reflection).name
source_preloader.send(:owners).each do |owner|
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection_name)
end
end
end
super
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
def instantiate(result_set, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
def construct(ar_parent, parent, row, seen, model_cache)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::Association.prepend(
Module.new do
def inversed_from(record)
if Bullet.start?
Bullet::Detector::NPlusOneQuery.add_inversed_object(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
association = owner.association(reflection.through_reflection.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) unless @inversed
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def target
result = super()
if Bullet.start?
if owner.class.name !~ /^HABTM_/ && !@inversed
if is_a? ::ActiveRecord::Associations::ThroughAssociation
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.through_reflection.name)
association = owner.association(reflection.through_reflection.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if reflection.through_reflection != through_reflection
Bullet::Detector::NPlusOneQuery.call_association(owner, through_reflection.name)
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/mongoid9x.rb | lib/bullet/mongoid9x.rb | # frozen_string_literal: true
module Bullet
module Mongoid
def self.enable
require 'mongoid'
require 'rubygems'
::Mongoid::Contextual::Mongo.class_eval do
alias_method :origin_first, :first
alias_method :origin_last, :last
alias_method :origin_each, :each
alias_method :origin_eager_load, :eager_load
%i[first last].each do |context|
default = Gem::Version.new(::Mongoid::VERSION) >= Gem::Version.new('7.5') ? nil : {}
define_method(context) do |opts = default|
result = send(:"origin_#{context}", opts)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
result
end
end
def each(&_block)
return to_enum unless block_given?
first_document = nil
document_count = 0
origin_each do |document|
document_count += 1
if document_count == 1
first_document = document
elsif document_count == 2
Bullet::Detector::NPlusOneQuery.add_possible_objects([first_document, document])
yield(first_document)
first_document = nil
yield(document)
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(document)
yield(document)
end
end
if document_count == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(first_document)
yield(first_document)
end
self
end
def eager_load(docs)
associations = criteria.inclusions.map(&:name)
docs.each { |doc| Bullet::Detector::NPlusOneQuery.add_object_associations(doc, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(docs, associations)
origin_eager_load(docs)
end
end
::Mongoid::Association::Accessors.class_eval do
alias_method :origin_get_relation, :get_relation
private
def get_relation(name, association, object, reload = false)
result = origin_get_relation(name, association, object, reload)
Bullet::Detector::NPlusOneQuery.call_association(self, name) unless association.embedded?
result
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record5.rb | lib/bullet/active_record5.rb | # frozen_string_literal: true
module Bullet
module SaveWithBulletSupport
def _create_record(*)
super do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
yield(self) if block_given?
end
end
end
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.extend(
Module.new do
def find_by_sql(sql, binds = [], preparable: nil, &block)
result = super
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
)
::ActiveRecord::Base.prepend(SaveWithBulletSupport)
::ActiveRecord::Relation.prepend(
Module.new do
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def records
result = super
if Bullet.start?
if result.first.class.name !~ /^HABTM_/
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
end
end
result
end
end
)
::ActiveRecord::Associations::Preloader.prepend(
Module.new do
def preloaders_for_one(association, records, scope)
if Bullet.start?
records.compact!
if records.first.class.name !~ /^HABTM_/
records.each { |record| Bullet::Detector::Association.add_object_associations(record, association) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, association)
end
end
super
end
end
)
::ActiveRecord::FinderMethods.prepend(
Module.new do
# add includes in scope
def find_with_associations
return super { |r| yield r } if block_given?
records = super
if Bullet.start?
associations = (eager_load_values + includes_values).uniq
records.each { |record| Bullet::Detector::Association.add_object_associations(record, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, associations)
end
records
end
end
)
::ActiveRecord::Associations::JoinDependency.prepend(
Module.new do
if ::ActiveRecord::Associations::JoinDependency.instance_method(:instantiate).parameters.last[0] == :block
# ActiveRecord >= 5.1.5
def instantiate(result_set, &block)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
else
# ActiveRecord <= 5.1.4
def instantiate(result_set, aliases)
@bullet_eager_loadings = {}
records = super
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(
objects,
eager_loadings_hash[objects.first].to_a
)
end
end
records
end
end
def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
super
end
# call join associations
def construct_model(record, node, row, model_cache, id, aliases)
result = super
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.through_reflection?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
)
::ActiveRecord::Associations::CollectionAssociation.prepend(
Module.new do
def load_target
records = super
if Bullet.start?
if is_a? ::ActiveRecord::Associations::ThroughAssociation
refl = reflection.through_reflection
association = owner.association(refl.name)
if association.loaded?
Bullet::Detector::NPlusOneQuery.call_association(owner, refl.name)
Array.wrap(association.target).each do |through_record|
Bullet::Detector::NPlusOneQuery.call_association(through_record, source_reflection.name)
end
if refl.through_reflection?
refl = refl.through_reflection while refl.through_reflection?
Bullet::Detector::NPlusOneQuery.call_association(owner, refl.name)
end
end
end
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) unless @inversed
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
def empty?
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
super
end
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name) if Bullet.start?
super
end
end
)
::ActiveRecord::Associations::SingularAssociation.prepend(
Module.new do
# call has_one and belongs_to associations
def target
result = super()
if Bullet.start?
if owner.class.name !~ /^HABTM_/ && !@inversed
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
)
::ActiveRecord::Associations::HasManyAssociation.prepend(
Module.new do
def empty?
result = super
if Bullet.start? && !reflection.has_cached_counter?
Bullet::Detector::NPlusOneQuery.call_association(owner, reflection.name)
end
result
end
def count_records
result = reflection.has_cached_counter?
if Bullet.start? && !result && !is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(owner, reflection.name)
end
super
end
end
)
::ActiveRecord::Associations::CollectionProxy.prepend(
Module.new do
def count(column_name = nil)
if Bullet.start? && !proxy_association.is_a?(::ActiveRecord::Associations::ThroughAssociation)
Bullet::Detector::CounterCache.add_counter_cache(
proxy_association.owner,
proxy_association.reflection.name
)
Bullet::Detector::NPlusOneQuery.call_association(
proxy_association.owner,
proxy_association.reflection.name
)
end
super(column_name)
end
end
)
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/detector.rb | lib/bullet/detector.rb | # frozen_string_literal: true
module Bullet
module Detector
autoload :Base, 'bullet/detector/base'
autoload :Association, 'bullet/detector/association'
autoload :NPlusOneQuery, 'bullet/detector/n_plus_one_query'
autoload :UnusedEagerLoading, 'bullet/detector/unused_eager_loading'
autoload :CounterCache, 'bullet/detector/counter_cache'
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/active_record42.rb | lib/bullet/active_record42.rb | # frozen_string_literal: true
module Bullet
module ActiveRecord
def self.enable
require 'active_record'
::ActiveRecord::Base.class_eval do
class << self
alias_method :origin_find, :find
def find(*args)
result = origin_find(*args)
if Bullet.start?
if result.is_a? Array
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
alias_method :origin_find_by_sql, :find_by_sql
def find_by_sql(sql, binds = [])
result = origin_find_by_sql(sql, binds)
if Bullet.start?
if result.is_a? Array
if result.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(result)
Bullet::Detector::CounterCache.add_possible_objects(result)
elsif result.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(result.first)
Bullet::Detector::CounterCache.add_impossible_object(result.first)
end
elsif result.is_a? ::ActiveRecord::Base
Bullet::Detector::NPlusOneQuery.add_impossible_object(result)
Bullet::Detector::CounterCache.add_impossible_object(result)
end
end
result
end
end
end
::ActiveRecord::Persistence.class_eval do
def _create_record_with_bullet(*args)
_create_record_without_bullet(*args).tap do
Bullet::Detector::NPlusOneQuery.update_inversed_object(self)
Bullet::Detector::NPlusOneQuery.add_impossible_object(self)
end
end
alias_method_chain :_create_record, :bullet
end
::ActiveRecord::Relation.class_eval do
alias_method :origin_to_a, :to_a
# if select a collection of objects, then these objects have possible to cause N+1 query.
# if select only one object, then the only one object has impossible to cause N+1 query.
def to_a
records = origin_to_a
if Bullet.start?
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
end
::ActiveRecord::Associations::Preloader.class_eval do
alias_method :origin_preloaders_on, :preloaders_on
def preloaders_on(association, records, scope)
if Bullet.start?
records.compact!
if records.first.class.name !~ /^HABTM_/
records.each { |record| Bullet::Detector::Association.add_object_associations(record, association) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, association)
end
end
origin_preloaders_on(association, records, scope)
end
end
::ActiveRecord::FinderMethods.class_eval do
# add includes in scope
alias_method :origin_find_with_associations, :find_with_associations
def find_with_associations
return origin_find_with_associations { |r| yield r } if block_given?
records = origin_find_with_associations
if Bullet.start?
associations = (eager_load_values + includes_values).uniq
records.each { |record| Bullet::Detector::Association.add_object_associations(record, associations) }
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(records, associations)
end
records
end
end
::ActiveRecord::Associations::JoinDependency.class_eval do
alias_method :origin_instantiate, :instantiate
alias_method :origin_construct, :construct
alias_method :origin_construct_model, :construct_model
def instantiate(result_set, aliases)
@bullet_eager_loadings = {}
records = origin_instantiate(result_set, aliases)
if Bullet.start?
@bullet_eager_loadings.each do |_klazz, eager_loadings_hash|
objects = eager_loadings_hash.keys
Bullet::Detector::UnusedEagerLoading.add_eager_loadings(objects, eager_loadings_hash[objects.first].to_a)
end
end
records
end
def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
if Bullet.start?
unless ar_parent.nil?
parent.children.each do |node|
key = aliases.column_alias(node, node.primary_key)
id = row[key]
next unless id.nil?
associations = [node.reflection.name]
if node.reflection.nested?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(ar_parent, association)
Bullet::Detector::NPlusOneQuery.call_association(ar_parent, association)
@bullet_eager_loadings[ar_parent.class] ||= {}
@bullet_eager_loadings[ar_parent.class][ar_parent] ||= Set.new
@bullet_eager_loadings[ar_parent.class][ar_parent] << association
end
end
end
end
origin_construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
end
# call join associations
def construct_model(record, node, row, model_cache, id, aliases)
result = origin_construct_model(record, node, row, model_cache, id, aliases)
if Bullet.start?
associations = [node.reflection.name]
if node.reflection.nested?
associations << node.reflection.through_reflection.name
end
associations.each do |association|
Bullet::Detector::Association.add_object_associations(record, association)
Bullet::Detector::NPlusOneQuery.call_association(record, association)
@bullet_eager_loadings[record.class] ||= {}
@bullet_eager_loadings[record.class][record] ||= Set.new
@bullet_eager_loadings[record.class][record] << association
end
end
result
end
end
::ActiveRecord::Associations::CollectionAssociation.class_eval do
# call one to many associations
alias_method :origin_load_target, :load_target
def load_target
records = origin_load_target
if Bullet.start?
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) unless @inversed
if records.first.class.name !~ /^HABTM_/
if records.size > 1
Bullet::Detector::NPlusOneQuery.add_possible_objects(records)
Bullet::Detector::CounterCache.add_possible_objects(records)
elsif records.size == 1
Bullet::Detector::NPlusOneQuery.add_impossible_object(records.first)
Bullet::Detector::CounterCache.add_impossible_object(records.first)
end
end
end
records
end
alias_method :origin_empty?, :empty?
def empty?
if Bullet.start? && !has_cached_counter?(@reflection)
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name)
end
origin_empty?
end
alias_method :origin_include?, :include?
def include?(object)
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) if Bullet.start?
origin_include?(object)
end
end
::ActiveRecord::Associations::SingularAssociation.class_eval do
# call has_one and belongs_to associations
alias_method :origin_reader, :reader
def reader(force_reload = false)
result = origin_reader(force_reload)
if Bullet.start?
if @owner.class.name !~ /^HABTM_/ && !@inversed
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name)
if Bullet::Detector::NPlusOneQuery.impossible?(@owner)
Bullet::Detector::NPlusOneQuery.add_impossible_object(result) if result
else
Bullet::Detector::NPlusOneQuery.add_possible_objects(result) if result
end
end
end
result
end
end
::ActiveRecord::Associations::HasManyAssociation.class_eval do
alias_method :origin_many_empty?, :empty?
def empty?
result = origin_many_empty?
if Bullet.start? && !has_cached_counter?(@reflection)
Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name)
end
result
end
alias_method :origin_count_records, :count_records
def count_records
result = has_cached_counter?
Bullet::Detector::CounterCache.add_counter_cache(@owner, @reflection.name) if Bullet.start? && !result
origin_count_records
end
end
::ActiveRecord::Associations::CollectionProxy.class_eval do
def count(column_name = nil, options = {})
if Bullet.start?
Bullet::Detector::CounterCache.add_counter_cache(proxy_association.owner, proxy_association.reflection.name)
Bullet::Detector::NPlusOneQuery.call_association(proxy_association.owner, proxy_association.reflection.name)
end
super(column_name, options)
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/dependency.rb | lib/bullet/dependency.rb | # frozen_string_literal: true
module Bullet
module Dependency
def mongoid?
@mongoid ||= defined?(::Mongoid)
end
def active_record?
@active_record ||= defined?(::ActiveRecord)
end
def active_record_version
@active_record_version ||=
begin
if active_record40?
'active_record4'
elsif active_record41?
'active_record41'
elsif active_record42?
'active_record42'
elsif active_record50?
'active_record5'
elsif active_record51?
'active_record5'
elsif active_record52?
'active_record52'
elsif active_record60?
'active_record60'
elsif active_record61?
'active_record61'
elsif active_record70?
'active_record70'
elsif active_record71?
'active_record71'
elsif active_record72?
'active_record72'
elsif active_record80?
'active_record80'
elsif active_record81?
'active_record81'
else
raise "Bullet does not support active_record #{::ActiveRecord::VERSION::STRING} yet"
end
end
end
def mongoid_version
@mongoid_version ||=
begin
if mongoid4x?
'mongoid4x'
elsif mongoid5x?
'mongoid5x'
elsif mongoid6x?
'mongoid6x'
elsif mongoid7x?
'mongoid7x'
elsif mongoid8x?
'mongoid8x'
elsif mongoid9x?
'mongoid9x'
else
raise "Bullet does not support mongoid #{::Mongoid::VERSION} yet"
end
end
end
def active_record4?
active_record? && ::ActiveRecord::VERSION::MAJOR == 4
end
def active_record5?
active_record? && ::ActiveRecord::VERSION::MAJOR == 5
end
def active_record6?
active_record? && ::ActiveRecord::VERSION::MAJOR == 6
end
def active_record7?
active_record? && ::ActiveRecord::VERSION::MAJOR == 7
end
def active_record8?
active_record? && ::ActiveRecord::VERSION::MAJOR == 8
end
def active_record40?
active_record4? && ::ActiveRecord::VERSION::MINOR == 0
end
def active_record41?
active_record4? && ::ActiveRecord::VERSION::MINOR == 1
end
def active_record42?
active_record4? && ::ActiveRecord::VERSION::MINOR == 2
end
def active_record50?
active_record5? && ::ActiveRecord::VERSION::MINOR == 0
end
def active_record51?
active_record5? && ::ActiveRecord::VERSION::MINOR == 1
end
def active_record52?
active_record5? && ::ActiveRecord::VERSION::MINOR == 2
end
def active_record60?
active_record6? && ::ActiveRecord::VERSION::MINOR == 0
end
def active_record61?
active_record6? && ::ActiveRecord::VERSION::MINOR == 1
end
def active_record70?
active_record7? && ::ActiveRecord::VERSION::MINOR == 0
end
def active_record71?
active_record7? && ::ActiveRecord::VERSION::MINOR == 1
end
def active_record72?
active_record7? && ::ActiveRecord::VERSION::MINOR == 2
end
def active_record80?
active_record8? && ::ActiveRecord::VERSION::MINOR == 0
end
def active_record81?
active_record8? && ::ActiveRecord::VERSION::MINOR == 1
end
def mongoid4x?
mongoid? && ::Mongoid::VERSION =~ /\A4/
end
def mongoid5x?
mongoid? && ::Mongoid::VERSION =~ /\A5/
end
def mongoid6x?
mongoid? && ::Mongoid::VERSION =~ /\A6/
end
def mongoid7x?
mongoid? && ::Mongoid::VERSION =~ /\A7/
end
def mongoid8x?
mongoid? && ::Mongoid::VERSION =~ /\A8/
end
def mongoid9x?
mongoid? && ::Mongoid::VERSION =~ /\A9/
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/notification.rb | lib/bullet/notification.rb | # frozen_string_literal: true
module Bullet
module Notification
autoload :Base, 'bullet/notification/base'
autoload :UnusedEagerLoading, 'bullet/notification/unused_eager_loading'
autoload :NPlusOneQuery, 'bullet/notification/n_plus_one_query'
autoload :CounterCache, 'bullet/notification/counter_cache'
class UnoptimizedQueryError < StandardError
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/detector/counter_cache.rb | lib/bullet/detector/counter_cache.rb | # frozen_string_literal: true
using Bullet::Ext::Object
module Bullet
module Detector
class CounterCache < Base
class << self
def add_counter_cache(object, associations)
return unless Bullet.start?
return unless Bullet.counter_cache_enable?
return unless object.bullet_primary_key_value
Bullet.debug(
'Detector::CounterCache#add_counter_cache',
"object: #{object.bullet_key}, associations: #{associations}"
)
create_notification object.class.to_s, associations if conditions_met?(object, associations)
end
def add_possible_objects(object_or_objects)
return unless Bullet.start?
return unless Bullet.counter_cache_enable?
objects = Array.wrap(object_or_objects)
return if objects.map(&:bullet_primary_key_value).compact.empty?
Bullet.debug(
'Detector::CounterCache#add_possible_objects',
"objects: #{objects.map(&:bullet_key).join(', ')}"
)
objects.each { |object| possible_objects.add object.bullet_key }
end
def add_impossible_object(object)
return unless Bullet.start?
return unless Bullet.counter_cache_enable?
return unless object.bullet_primary_key_value
Bullet.debug('Detector::CounterCache#add_impossible_object', "object: #{object.bullet_key}")
impossible_objects.add object.bullet_key
end
def conditions_met?(object, _associations)
possible_objects.include?(object.bullet_key) && !impossible_objects.include?(object.bullet_key)
end
def possible_objects
Thread.current.thread_variable_get(:bullet_counter_possible_objects)
end
def impossible_objects
Thread.current.thread_variable_get(:bullet_counter_impossible_objects)
end
private
def create_notification(klazz, associations)
notify_associations = Array.wrap(associations) - Bullet.get_safelist_associations(:counter_cache, klazz)
if notify_associations.present?
notice = Bullet::Notification::CounterCache.new klazz, notify_associations
Bullet.notification_collector.add notice
end
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/detector/n_plus_one_query.rb | lib/bullet/detector/n_plus_one_query.rb | # frozen_string_literal: true
using Bullet::Ext::Object
module Bullet
module Detector
class NPlusOneQuery < Association
extend Dependency
extend StackTraceFilter
class << self
# executed when object.associations is called.
# first, it keeps this method call for object.association.
# then, it checks if this associations call is unpreload.
# if it is, keeps this unpreload associations and caller.
def call_association(object, associations)
return unless Bullet.start?
return unless Bullet.n_plus_one_query_enable?
return unless object.bullet_primary_key_value
return if inversed_objects.include?(object.bullet_key, associations)
add_call_object_associations(object, associations)
Bullet.debug(
'Detector::NPlusOneQuery#call_association',
"object: #{object.bullet_key}, associations: #{associations}"
)
if !excluded_stacktrace_path? && conditions_met?(object, associations)
Bullet.debug('detect n + 1 query', "object: #{object.bullet_key}, associations: #{associations}")
create_notification(caller_in_project(object.bullet_key), object.class.to_s, associations)
end
end
def add_possible_objects(object_or_objects)
return unless Bullet.start?
return unless Bullet.n_plus_one_query_enable?
objects = Array.wrap(object_or_objects)
class_names_match_regex = true
primary_key_values_are_empty = true
keys_joined = objects.map do |obj|
unless obj.class.name =~ /^HABTM_/
class_names_match_regex = false
end
unless obj.bullet_primary_key_value.nil?
primary_key_values_are_empty = false
end
obj.bullet_key
end.join(", ")
unless class_names_match_regex || primary_key_values_are_empty
Bullet.debug('Detector::NPlusOneQuery#add_possible_objects', "objects: #{keys_joined}")
objects.each { |object| possible_objects.add object.bullet_key }
end
end
def add_impossible_object(object)
return unless Bullet.start?
return unless Bullet.n_plus_one_query_enable?
return unless object.bullet_primary_key_value
Bullet.debug('Detector::NPlusOneQuery#add_impossible_object', "object: #{object.bullet_key}")
impossible_objects.add object.bullet_key
end
def add_inversed_object(object, association)
return unless Bullet.start?
return unless Bullet.n_plus_one_query_enable?
object_key = object.bullet_primary_key_value ? object.bullet_key : object.object_id
Bullet.debug(
'Detector::NPlusOneQuery#add_inversed_object',
"object: #{object_key}, association: #{association}"
)
inversed_objects.add object_key, association
end
def update_inversed_object(object)
if inversed_objects&.key?(object.object_id)
Bullet.debug(
'Detector::NPlusOneQuery#update_inversed_object',
"object from #{object.object_id} to #{object.bullet_key}"
)
inversed_objects.add(object.bullet_key, inversed_objects[object.object_id].to_a)
end
end
# decide whether the object.associations is unpreloaded or not.
def conditions_met?(object, associations)
possible?(object) && !impossible?(object) && !association?(object, associations)
end
def possible?(object)
possible_objects.include? object.bullet_key
end
def impossible?(object)
impossible_objects.include? object.bullet_key
end
# check if object => associations already exists in object_associations.
def association?(object, associations)
value = object_associations[object.bullet_key]
value&.each do |v|
# associations == v comparison order is important here because
# v variable might be a squeel node where :== method is redefined,
# so it does not compare values at all and return unexpected results
result = v.is_a?(Hash) ? v.key?(associations) : associations == v
return true if result
end
false
end
private
def create_notification(callers, klazz, associations)
notify_associations = Array.wrap(associations) - Bullet.get_safelist_associations(:n_plus_one_query, klazz)
if notify_associations.present?
notice = Bullet::Notification::NPlusOneQuery.new(callers, klazz, notify_associations)
Bullet.notification_collector.add(notice)
end
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/detector/base.rb | lib/bullet/detector/base.rb | # frozen_string_literal: true
module Bullet
module Detector
class Base
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/detector/unused_eager_loading.rb | lib/bullet/detector/unused_eager_loading.rb | # frozen_string_literal: true
using Bullet::Ext::Object
using Bullet::Ext::String
module Bullet
module Detector
class UnusedEagerLoading < Association
extend Dependency
extend StackTraceFilter
class << self
# check if there are unused preload associations.
# get related_objects from eager_loadings associated with object and associations
# get call_object_association from associations of call_object_associations whose object is in related_objects
# if association not in call_object_association, then the object => association - call_object_association is unused preload associations
def check_unused_preload_associations
return unless Bullet.start?
return unless Bullet.unused_eager_loading_enable?
object_associations.each do |bullet_key, associations|
object_association_diff = diff_object_associations bullet_key, associations
next if object_association_diff.empty?
Bullet.debug('detect unused preload', "object: #{bullet_key}, associations: #{object_association_diff}")
create_notification(caller_in_project(bullet_key), bullet_key.bullet_class_name, object_association_diff)
end
end
def add_eager_loadings(objects, associations)
return unless Bullet.start?
return unless Bullet.unused_eager_loading_enable?
return if objects.map(&:bullet_primary_key_value).compact.empty?
Bullet.debug(
'Detector::UnusedEagerLoading#add_eager_loadings',
"objects: #{objects.map(&:bullet_key).join(', ')}, associations: #{associations}"
)
bullet_keys = objects.map(&:bullet_key)
to_add = []
to_merge = []
to_delete = []
eager_loadings.each do |k, _v|
key_objects_overlap = k & bullet_keys
next if key_objects_overlap.empty?
bullet_keys -= k
if key_objects_overlap == k
to_add << [k, associations]
else
to_merge << [key_objects_overlap, (eager_loadings[k].dup << associations)]
keys_without_objects = k - key_objects_overlap
to_merge << [keys_without_objects, eager_loadings[k]]
to_delete << k
end
end
to_add.each { |k, val| eager_loadings.add k, val }
to_merge.each { |k, val| eager_loadings.merge k, val }
to_delete.each { |k| eager_loadings.delete k }
eager_loadings.add bullet_keys, associations unless bullet_keys.empty?
end
private
def create_notification(callers, klazz, associations)
notify_associations = Array.wrap(associations) - Bullet.get_safelist_associations(
:unused_eager_loading,
klazz
)
if notify_associations.present?
notice = Bullet::Notification::UnusedEagerLoading.new(callers, klazz, notify_associations)
Bullet.notification_collector.add(notice)
end
end
def call_associations(bullet_key, associations)
all = Set.new
eager_loadings.similarly_associated(bullet_key, associations).each do |related_bullet_key|
coa = call_object_associations[related_bullet_key]
next if coa.nil?
all.merge coa
end
all.to_a
end
def diff_object_associations(bullet_key, associations)
potential_associations = associations - call_associations(bullet_key, associations)
potential_associations.reject { |a| a.is_a?(Hash) }
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/detector/association.rb | lib/bullet/detector/association.rb | # frozen_string_literal: true
using Bullet::Ext::Object
module Bullet
module Detector
class Association < Base
class << self
def add_object_associations(object, associations)
return unless Bullet.start?
return if !Bullet.n_plus_one_query_enable? && !Bullet.unused_eager_loading_enable?
return unless object.bullet_primary_key_value
Bullet.debug(
'Detector::Association#add_object_associations',
"object: #{object.bullet_key}, associations: #{associations}"
)
call_stacks.add(object.bullet_key)
object_associations.add(object.bullet_key, associations)
end
def add_call_object_associations(object, associations)
return unless Bullet.start?
return if !Bullet.n_plus_one_query_enable? && !Bullet.unused_eager_loading_enable?
return unless object.bullet_primary_key_value
Bullet.debug(
'Detector::Association#add_call_object_associations',
"object: #{object.bullet_key}, associations: #{associations}"
)
call_stacks.add(object.bullet_key)
call_object_associations.add(object.bullet_key, associations)
end
# possible_objects keep the class to object relationships
# that the objects may cause N+1 query.
# e.g. { Post => ["Post:1", "Post:2"] }
def possible_objects
Thread.current.thread_variable_get(:bullet_possible_objects)
end
# impossible_objects keep the class to objects relationships
# that the objects may not cause N+1 query.
# e.g. { Post => ["Post:1", "Post:2"] }
# if find collection returns only one object, then the object is impossible object,
# impossible_objects are used to avoid treating 1+1 query to N+1 query.
def impossible_objects
Thread.current.thread_variable_get(:bullet_impossible_objects)
end
private
# object_associations keep the object relationships
# that the object has many associations.
# e.g. { "Post:1" => [:comments] }
# the object_associations keep all associations that may be or may no be
# unpreload associations or unused preload associations.
def object_associations
Thread.current.thread_variable_get(:bullet_object_associations)
end
# call_object_associations keep the object relationships
# that object.associations is called.
# e.g. { "Post:1" => [:comments] }
# they are used to detect unused preload associations.
def call_object_associations
Thread.current.thread_variable_get(:bullet_call_object_associations)
end
# inversed_objects keeps object relationships
# that association is inversed.
# e.g. { "Comment:1" => ["post"] }
def inversed_objects
Thread.current.thread_variable_get(:bullet_inversed_objects)
end
# eager_loadings keep the object relationships
# that the associations are preloaded by find :include.
# e.g. { ["Post:1", "Post:2"] => [:comments, :user] }
def eager_loadings
Thread.current.thread_variable_get(:bullet_eager_loadings)
end
# call_stacks keeps stacktraces where querie-objects were called from.
# e.g. { 'Object:111' => [SomeProject/app/controllers/...] }
def call_stacks
Thread.current.thread_variable_get(:bullet_call_stacks)
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/notification/counter_cache.rb | lib/bullet/notification/counter_cache.rb | # frozen_string_literal: true
module Bullet
module Notification
class CounterCache < Base
def body
klazz_associations_str
end
def title
'Need Counter Cache with Active Record size'
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/notification/n_plus_one_query.rb | lib/bullet/notification/n_plus_one_query.rb | # frozen_string_literal: true
module Bullet
module Notification
class NPlusOneQuery < Base
def initialize(callers, base_class, associations, path = nil)
super(base_class, associations, path)
@callers = callers
end
def body
"#{klazz_associations_str}\n Add to your query: #{associations_str}"
end
def title
"USE eager loading #{@path ? "in #{@path}" : 'detected'}"
end
def notification_data
super.merge(backtrace: [])
end
protected
def call_stack_messages
(['Call stack'] + @callers).join("\n ")
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/notification/base.rb | lib/bullet/notification/base.rb | # frozen_string_literal: true
module Bullet
module Notification
class Base
attr_accessor :notifier, :url
attr_reader :base_class, :associations, :path
def initialize(base_class, association_or_associations, path = nil)
@base_class = base_class
@associations =
association_or_associations.is_a?(Array) ? association_or_associations : [association_or_associations]
@path = path
end
def title
raise NoMethodError, 'no method title defined'
end
def body
raise NoMethodError, 'no method body defined'
end
def call_stack_messages
''
end
def whoami
@user ||=
ENV['USER'].presence ||
(
begin
`whoami`.chomp
rescue StandardError
''
end
)
@user.present? ? "user: #{@user}" : ''
end
def body_with_caller
"#{body}\n#{call_stack_messages}\n"
end
def notify_inline
notifier.inline_notify(notification_data)
end
def notify_out_of_channel
notifier.out_of_channel_notify(notification_data)
end
def short_notice
parts = []
parts << whoami.presence unless Bullet.skip_user_in_notification
parts << url
parts << title
parts << body
parts.compact.join(' ')
end
def notification_data
hash = {}
hash[:user] = whoami unless Bullet.skip_user_in_notification
hash[:url] = url
hash[:title] = title
hash[:body] = body_with_caller
hash
end
def eql?(other)
self.class == other.class && klazz_associations_str == other.klazz_associations_str
end
def hash
[self.class, klazz_associations_str].hash
end
protected
def klazz_associations_str
" #{@base_class} => [#{@associations.map(&:inspect).join(', ')}]"
end
def associations_str
".includes(#{@associations.map { |a| a.to_s.to_sym }
.inspect})"
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/notification/unused_eager_loading.rb | lib/bullet/notification/unused_eager_loading.rb | # frozen_string_literal: true
module Bullet
module Notification
class UnusedEagerLoading < Base
def initialize(callers, base_class, associations, path = nil)
super(base_class, associations, path)
@callers = callers
end
def body
"#{klazz_associations_str}\n Remove from your query: #{associations_str}"
end
def title
"AVOID eager loading #{@path ? "in #{@path}" : 'detected'}"
end
def notification_data
super.merge(backtrace: [])
end
protected
def call_stack_messages
(['Call stack'] + @callers).join("\n ")
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/ext/string.rb | lib/bullet/ext/string.rb | # frozen_string_literal: true
module Bullet
module Ext
module String
refine ::String do
def bullet_class_name
last_colon = self.rindex(':')
last_colon ? self[0...last_colon].dup : self.dup
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/ext/object.rb | lib/bullet/ext/object.rb | # frozen_string_literal: true
module Bullet
module Ext
module Object
refine ::Object do
attr_writer :bullet_key, :bullet_primary_key_value
def bullet_key
return "#{self.class}:" if respond_to?(:persisted?) && !persisted?
@bullet_key ||= "#{self.class}:#{bullet_primary_key_value}"
end
def bullet_primary_key_value
return if respond_to?(:persisted?) && !persisted?
@bullet_primary_key_value ||=
begin
primary_key = self.class.try(:primary_keys) || self.class.try(:primary_key) || :id
bullet_join_potential_composite_primary_key(primary_key)
end
end
private
def bullet_join_potential_composite_primary_key(primary_keys)
return read_attribute(primary_keys) unless primary_keys.is_a?(Enumerable)
primary_keys.map { |primary_key| read_attribute primary_key }
.compact.join(',')
end
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/registry/base.rb | lib/bullet/registry/base.rb | # frozen_string_literal: true
module Bullet
module Registry
class Base
attr_reader :registry
def initialize
@registry = {}
end
def [](key)
@registry[key]
end
def each(&block)
@registry.each(&block)
end
def delete(base)
@registry.delete(base)
end
def select(*args, &block)
@registry.select(*args, &block)
end
def add(key, value)
@registry[key] ||= Set.new
if value.is_a? Array
@registry[key] += value
else
@registry[key] << value
end
end
def include?(key, value)
key?(key) && @registry[key].include?(value)
end
def key?(key)
@registry.key?(key)
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/registry/object.rb | lib/bullet/registry/object.rb | # frozen_string_literal: true
using Bullet::Ext::Object
using Bullet::Ext::String
module Bullet
module Registry
class Object < Base
def add(bullet_key)
super(bullet_key.bullet_class_name, bullet_key)
end
def include?(bullet_key)
super(bullet_key.bullet_class_name, bullet_key)
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/registry/association.rb | lib/bullet/registry/association.rb | # frozen_string_literal: true
module Bullet
module Registry
class Association < Base
def merge(base, associations)
@registry.merge!(base => associations)
end
def similarly_associated(base, associations)
@registry.select { |key, value| key.include?(base) && value == associations }
.collect(&:first).flatten
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.