diff --git a/lib/bullet/detector/n_plus_one_query.rb b/lib/bullet/detector/n_plus_one_query.rb index 7a6600e1..650ea3c9 100644 --- a/lib/bullet/detector/n_plus_one_query.rb +++ b/lib/bullet/detector/n_plus_one_query.rb @@ -27,7 +27,7 @@ def call_association(object, 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 + create_notification(caller_in_project(object.bullet_key), object.class.to_s, associations) end end @@ -38,16 +38,16 @@ def add_possible_objects(object_or_objects) objects = Array.wrap(object_or_objects) class_names_match_regex = true primary_key_values_are_empty = true - keys_joined = "" - objects.each do |obj| + + 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 - keys_joined += "#{(keys_joined.empty? ? '' : ', ')}#{obj.bullet_key}" - 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 } diff --git a/lib/bullet/ext/object.rb b/lib/bullet/ext/object.rb index 68dfbc87..f8e60cbb 100644 --- a/lib/bullet/ext/object.rb +++ b/lib/bullet/ext/object.rb @@ -4,22 +4,20 @@ module Bullet module Ext module Object refine ::Object do + attr_writer :bullet_key, :bullet_primary_key_value + def bullet_key - "#{self.class}:#{bullet_primary_key_value}" + @bullet_key ||= "#{self.class}:#{bullet_primary_key_value}" end def bullet_primary_key_value - return if respond_to?(:persisted?) && !persisted? - - if self.class.respond_to?(:primary_keys) && self.class.primary_keys - primary_key = self.class.primary_keys - elsif self.class.respond_to?(:primary_key) && self.class.primary_key - primary_key = self.class.primary_key - else - primary_key = :id - end + @bullet_primary_key_value ||= begin + return if respond_to?(:persisted?) && !persisted? - bullet_join_potential_composite_primary_key(primary_key) + primary_key = self.class.try(:primary_keys) || self.class.try(:primary_key) || :id + + bullet_join_potential_composite_primary_key(primary_key) + end end private diff --git a/lib/bullet/ext/string.rb b/lib/bullet/ext/string.rb index 1b9e9413..ed4ee285 100644 --- a/lib/bullet/ext/string.rb +++ b/lib/bullet/ext/string.rb @@ -4,8 +4,13 @@ module Bullet module Ext module String refine ::String do + attr_reader :bullet_class_name + def bullet_class_name - sub(/:[^:]*?$/, '') + @bullet_class_name ||= begin + last_colon = self.rindex(':') + last_colon ? self[0...last_colon] : self + end end end end