Skip to content

Commit 9e2d6ff

Browse files
authored
MONGOID-5805 Short-circuit the logic in extract_attribute to fix performance regression (backport to 8.1-stable) (#5869)
* short-circuit the logic in extract_attribute to fix performance regression * short circuit on anything that's not a document or hash * handle hash/string keys
1 parent a549de2 commit 9e2d6ff

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

lib/mongoid/matcher.rb

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,25 @@ module Matcher
3535
# from and behaves identically to association traversal for the purposes
3636
# of, for example, subsequent array element retrieval.
3737
#
38-
# @param [ Document | Hash ] document The document to extract from.
38+
# @param [ Document | Hash | String ] document The document to extract from.
3939
# @param [ String ] key The key path to extract.
4040
#
4141
# @return [ Object | Array ] Field value or values.
4242
module_function def extract_attribute(document, key)
43+
# The matcher system will wind up sending atomic values to this as well,
44+
# when attepting to match more complex types. If anything other than a
45+
# Document or a Hash is given, we'll short-circuit the logic and just
46+
# return an empty array.
47+
return [] unless document.is_a?(Hash) || document.is_a?(Document)
48+
49+
# Performance optimization; if the key does not include a '.' character,
50+
# it must reference an immediate attribute of the document.
51+
unless key.include?('.')
52+
hash = document.respond_to?(:attributes) ? document.attributes : document
53+
key = find_exact_key(hash, key)
54+
return key ? [ hash[key] ] : []
55+
end
56+
4357
if document.respond_to?(:as_attributes, true)
4458
# If a document has hash fields, as_attributes would keep those fields
4559
# as Hash instances which do not offer indifferent access.

spec/mongoid/association/referenced/belongs_to/proxy_spec.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,10 @@
749749
person.save!
750750
end
751751

752+
# NOTE: there as a bad interdependency here, with the auto_save_spec.rb
753+
# file. If auto_save_spec.rb runs before this, the following specs fail
754+
# with "undefined method `nullify' for an instance of Person".
755+
752756
context "when parent exists" do
753757

754758
context "when child is destroyed" do

0 commit comments

Comments
 (0)