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

@@ -284,6 +284,29 @@ class AssociationTest < ActiveModel::TestCase
]
}, @root_hash)
end
def test_embed_ids_include_true_does_not_serialize_multiple_times
@post.recent_comment = @comment
@post_serializer_class.class_eval do
has_one :comment, :embed => :ids, :include => true
has_one :recent_comment, :embed => :ids, :include => true, :root => :comments
end
# Count how often the @comment record is serialized.
serialized_times = 0
@comment.class_eval do
define_method :read_attribute_for_serialization, lambda { |name|
serialized_times += 1 if name == :body
super(name)
}
end
include_bare! :comment
include_bare! :recent_comment
assert_equal 1, serialized_times
end
end
class InclusionTest < AssociationTest

View File

@@ -73,11 +73,13 @@ class SerializerTest < ActiveModel::TestCase
class CommentSerializer
def initialize(comment, options={})
@comment = comment
@object = comment
end
attr_reader :object
def serializable_hash
{ :title => @comment.read_attribute_for_serialization(:title) }
{ :title => @object.read_attribute_for_serialization(:title) }
end
def as_json(options=nil)