diff --git a/lib/mongoid/matcher.rb b/lib/mongoid/matcher.rb index 034fb071ef..26e8a251cf 100644 --- a/lib/mongoid/matcher.rb +++ b/lib/mongoid/matcher.rb @@ -35,11 +35,25 @@ module Matcher # from and behaves identically to association traversal for the purposes # of, for example, subsequent array element retrieval. # - # @param [ Document | Hash ] document The document to extract from. + # @param [ Document | Hash | String ] document The document to extract from. # @param [ String ] key The key path to extract. # # @return [ Object | Array ] Field value or values. module_function def extract_attribute(document, key) + # The matcher system will wind up sending atomic values to this as well, + # when attepting to match more complex types. If anything other than a + # Document or a Hash is given, we'll short-circuit the logic and just + # return an empty array. + return [] unless document.is_a?(Hash) || document.is_a?(Document) + + # Performance optimization; if the key does not include a '.' character, + # it must reference an immediate attribute of the document. + unless key.include?('.') + hash = document.respond_to?(:attributes) ? document.attributes : document + key = find_exact_key(hash, key) + return key ? [ hash[key] ] : [] + end + if document.respond_to?(:as_attributes, true) # If a document has hash fields, as_attributes would keep those fields # as Hash instances which do not offer indifferent access. diff --git a/spec/mongoid/association/referenced/belongs_to/proxy_spec.rb b/spec/mongoid/association/referenced/belongs_to/proxy_spec.rb index d19a69a372..373456cddc 100644 --- a/spec/mongoid/association/referenced/belongs_to/proxy_spec.rb +++ b/spec/mongoid/association/referenced/belongs_to/proxy_spec.rb @@ -749,6 +749,10 @@ person.save! end + # NOTE: there as a bad interdependency here, with the auto_save_spec.rb + # file. If auto_save_spec.rb runs before this, the following specs fail + # with "undefined method `nullify' for an instance of Person". + context "when parent exists" do context "when child is destroyed" do