Skip to content

Fragment cache + array payload compounds non-cached keys #904

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

Closed
apolzon opened this issue May 7, 2015 · 2 comments
Closed

Fragment cache + array payload compounds non-cached keys #904

apolzon opened this issue May 7, 2015 · 2 comments

Comments

@apolzon
Copy link

apolzon commented May 7, 2015

If you define a serializer with a fragment cache, such as

class TestSerializer < ActiveModel::Serializer
  cache key: "test", except: [:field1]
  attributes :field1, :field2
end

and then render in your controller, an array:

render json: resources, each_serializer: TestSerializer

the fragment cache's call to attribute (line 52) will continually add field1, such that if resources has 20 objects, by the end, field1 will be called 20 times for the last invocation of the TestSerializer.

I believe ActiveModel::Serializer.attribute should only concat the key onto @_attributes if it is not already present.
i.e., line 45 (in master) should be:

      @_attributes.concat [key] unless @_attributes.include? key

Also, since the @_attributes variable is at the class level, subsequent requests compound the issue even further.

@groyoh
Copy link
Member

groyoh commented May 18, 2015

Nice catch! It was indeed a bug which would also happen simply by calling multiple times .attributes or .attribute with the same attribute name. I don't know if this has any consequence on the behavior itself, but it might slow the overall system since we iterate over the @_attributes variable when calling #attributes.

I created a PR to fix this (#914).

@joaomdmoura
Copy link
Member

Tks @apolzon and @groyoh !
Indeed it was a great catch, and an important issue.
I'm running some benchmark test yet to check if it made some impact 😄

Update:
It has some good impact into fragment cache, I was looking forward to have some improvement in its performance, thank you both! ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants