Skip to content

MONGOID-5411 allow results to be returned as demongoized hashes #5877

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 23, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
modify the hash in-place as an optimization
  • Loading branch information
jamis committed Oct 14, 2024
commit df098f47780928a990a517d3eb2421735beee0fc
26 changes: 14 additions & 12 deletions lib/mongoid/contextual/mongo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,10 @@ def recursive_demongoize(field_name, value, is_translation)
# of the given hash as if it were the raw representation of a document of
# the given klass.
#
# @note this method will modify the given hash, in-place, for performance
# reasons. If you wish to preserve the original hash, duplicate it before
# passing it to this method.
#
# @param [ Document ] klass the Document class that the given hash ought
# to represent
# @param [ Hash | nil ] hash the Hash instance containing the values to
Expand All @@ -1001,28 +1005,26 @@ def recursive_demongoize(field_name, value, is_translation)
def demongoize_hash(klass, hash)
return nil unless hash

hash.each_with_object({}) do |(key, value), new_hash|
hash.each_key do |key|
value = hash[key]

# does the key represent a declared field on the document?
if (field = klass.fields[key])
new_hash[key] = field.demongoize(value)
hash[key] = field.demongoize(value)
next
end

# does the key represent an emebedded relation on the document?
aliased_name = klass.aliased_associations[key] || key
if (assoc = klass.relations[aliased_name])
new_hash[key] = case value
when Array then value.map { |hash| demongoize_hash(assoc.klass, hash) }
when Hash then demongoize_hash(assoc.klass, value)
else value
end
next
case value
when Array then value.each { |h| demongoize_hash(assoc.klass, h) }
when Hash then demongoize_hash(assoc.klass, value)
end
end

# if its not a field or a relation, then we just pass it through
# literally
new_hash[key] = value
end

hash
end

# Demongoize the value for the given field. If the field is nil or the
Expand Down
Loading