Skip to content

Commit dc52d0e

Browse files
authored
MONGOID-5805 Short-circuit the logic in extract_attribute to fix performance regression (#5868)
* 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 fc09714 commit dc52d0e

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
@@ -39,11 +39,25 @@ module Matcher
3939
# from and behaves identically to association traversal for the purposes
4040
# of, for example, subsequent array element retrieval.
4141
#
42-
# @param [ Document | Hash ] document The document to extract from.
42+
# @param [ Document | Hash | String ] document The document to extract from.
4343
# @param [ String ] key The key path to extract.
4444
#
4545
# @return [ Object | Array ] Field value or values.
4646
module_function def extract_attribute(document, key)
47+
# The matcher system will wind up sending atomic values to this as well,
48+
# when attepting to match more complex types. If anything other than a
49+
# Document or a Hash is given, we'll short-circuit the logic and just
50+
# return an empty array.
51+
return [] unless document.is_a?(Hash) || document.is_a?(Document)
52+
53+
# Performance optimization; if the key does not include a '.' character,
54+
# it must reference an immediate attribute of the document.
55+
unless key.include?('.')
56+
hash = document.respond_to?(:attributes) ? document.attributes : document
57+
key = find_exact_key(hash, key)
58+
return key ? [ hash[key] ] : []
59+
end
60+
4761
if document.respond_to?(:as_attributes, true)
4862
# If a document has hash fields, as_attributes would keep those fields
4963
# 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
@@ -751,6 +751,10 @@
751751
person.save!
752752
end
753753

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

756760
context "when child is destroyed" do

0 commit comments

Comments
 (0)