diff --git a/README.md b/README.md index c59a6b7..be2b3c6 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/test/jbuilder_template_test.rb b/test/jbuilder_template_test.rb index 1de7fd2..5ff3a79 100644 --- a/test/jbuilder_template_test.rb +++ b/test/jbuilder_template_test.rb @@ -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