jbuilder
jbuilder copied to clipboard
fix cache bug
Hi, I ran into a very strange situation.
json.array! [1,2,3] do |i|
json.cache! 'test' do
json.name 'cache'
end
json.id i
end
The code above will print
[
{"name":"cache","id":1},
{"name":"cache","id":3},
{"name":"cache","id":3}
]
If we move json.id on the top, it will work. The reason for that is when use cache! in the beginning of the block it will retrieve the same cached object from previous iteration and overwrite it. I think it is the same reason for this issue #330
Thanks for the pull request, and welcome! The Rails team is excited to review your changes, and you should hear from @pixeltrix (or someone else) soon.
If any changes to this PR are deemed necessary, please add them as extra commits. This ensures that the reviewer can see what has changed since they last reviewed the code. Due to the way GitHub handles out-of-date commits, this should also make it reasonably obvious what issues have or haven't been addressed. Large or tricky changes may require several passes of review and changes.
Please see the contribution instructions for more information.
After further investigation, this will only happen when using memory_store for the cache. It is actually caused by the behaviour of Rails cache. Please see below example
Rails.cache.write('user', {id: 1})
a = Rails.cache.read('user')
#=> {:id=>1}
a[:name] = "Hello"
Rails.cache.read('user')
#=> {:id=>1, :name => "Hello"}
I ran into this today. It would be great to get it fixed! Can someone address this PR?
One more bug, i think
json.cache_collection! [1,2,3] do |category|
next
end
result
{}
{}
{}
I know this is a million years old, but just stumbled over it. It strikes me as odd this is only happening in the memory store. That implies to me it should be fixed in the memory store. Anyone interested in digging deeper?
@dhh what version was this in? I've tried using @BenZhang's test and his cache commands and can't seem to reproduce in any version of 7.x
Looking at his sequence of commands suggests it's an example of rails/rails#36956:
Rails.cache.write('user', {id: 1})
a = Rails.cache.read('user')
#=> {:id=>1}
a[:name] = "Hello"
Rails.cache.read('user')
#=> {:id=>1, :name => "Hello"}
that's not been applicable since rails/rails#37210.
Ha. Makes sense. The initial report was ancient but hadn't seen any updates. Will close. Thanks @pixeltrix 🙏