Skip to content

Commit

Permalink
Add case for testing collection dependencies (#520)
Browse files Browse the repository at this point in the history
  • Loading branch information
robinvdvleuten authored Dec 2, 2021
1 parent eea7679 commit 21585cd
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,14 @@ json.array! @posts, partial: "posts/post", as: :post, cached: true
json.comments @post.comments, partial: "comments/comment", as: :comment, cached: true
```

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:

```ruby
json.array! @posts, partial: "posts/post", as: :post, cached: -> post { [post, current_user] }
```

This will include both records as part of the cache key and updating either of them will expire the cache.

## Formatting Keys

Keys can be auto formatted using `key_format!`, this can be used to convert
Expand Down
27 changes: 27 additions & 0 deletions test/jbuilder_template_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,33 @@ class JbuilderTemplateTest < ActiveSupport::TestCase
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end

test "supports the cached: ->() {} option" do
result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)

assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]

expected = {
"id" => 1,
"body" => "Post #1",
"author" => {
"first_name" => "David",
"last_name" => "Heinemeier Hansson"
}
}

assert_equal expected, Rails.cache.read("post-1/foo")

result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)

assert_equal 10, result.count
assert_equal "Post #5", result[4]["body"]
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end

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

0 comments on commit 21585cd

Please sign in to comment.