Skip to content

Commit 21585cd

Browse files
Add case for testing collection dependencies (#520)
1 parent eea7679 commit 21585cd

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,14 @@ json.array! @posts, partial: "posts/post", as: :post, cached: true
292292
json.comments @post.comments, partial: "comments/comment", as: :comment, cached: true
293293
```
294294

295+
If your collection cache depends on multiple sources (try to avoid this to keep things simple), you can name all these dependencies as part of a block that returns an array:
296+
297+
```ruby
298+
json.array! @posts, partial: "posts/post", as: :post, cached: -> post { [post, current_user] }
299+
```
300+
301+
This will include both records as part of the cache key and updating either of them will expire the cache.
302+
295303
## Formatting Keys
296304

297305
Keys can be auto formatted using `key_format!`, this can be used to convert

test/jbuilder_template_test.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,33 @@ class JbuilderTemplateTest < ActiveSupport::TestCase
317317
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
318318
assert_equal "Pavel", result[5]["author"]["first_name"]
319319
end
320+
321+
test "supports the cached: ->() {} option" do
322+
result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)
323+
324+
assert_equal 10, result.count
325+
assert_equal "Post #5", result[4]["body"]
326+
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
327+
assert_equal "Pavel", result[5]["author"]["first_name"]
328+
329+
expected = {
330+
"id" => 1,
331+
"body" => "Post #1",
332+
"author" => {
333+
"first_name" => "David",
334+
"last_name" => "Heinemeier Hansson"
335+
}
336+
}
337+
338+
assert_equal expected, Rails.cache.read("post-1/foo")
339+
340+
result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)
341+
342+
assert_equal 10, result.count
343+
assert_equal "Post #5", result[4]["body"]
344+
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
345+
assert_equal "Pavel", result[5]["author"]["first_name"]
346+
end
320347

321348
test "raises an error on a render call with the :layout option" do
322349
error = assert_raises NotImplementedError do

0 commit comments

Comments
 (0)