When objects are sideloaded multiple times, serialize them only once

To achieve this, we make the following change when sideloading: Instead
of serializing associations and discarding duplicate *hashes*, we
memorize the *objects* (records) that we have already serialized, and
only serialize those that are new.

This change is mostly transparent, and brings down serialization time
from 3.1 seconds to 1.0 seconds on my set of sample data.

There is one change in the behavior: If you sideload the same object
multiple times, and it yields different hashes, like so:

    embed :ids, include: true
    has_many :comments
    has_many :recent_comments, root: comments, serializer: CommentShortSerializer

then previously, it would be included multiple times, whereas now, the
first hash wins. (I haven't actually tested this.) I don't know that
either option is preferable. It's not covered by the test suite, and I
think it's an edge case that is OK to ignore entirely.
This commit is contained in:
Jo Liss
2012-10-29 22:06:50 +01:00
parent 28ee88ca9a
commit ee3cec3d0c
4 changed files with 45 additions and 13 deletions

View File

@@ -99,7 +99,12 @@ module ActiveModel
find_serializable(item).serializable_hash
end
end
alias serialize_many serialize
def serializables
associated_object.map do |item|
find_serializable(item)
end
end
def serialize_ids
# Use pluck or select_columns if available
@@ -149,9 +154,9 @@ module ActiveModel
end
end
def serialize_many
def serializables
object = associated_object
value = object && find_serializable(object).serializable_hash
value = object && find_serializable(object)
value ? [value] : []
end