Skip to content

Commit

Permalink
Add support for expires_in: when using render with collection:
Browse files Browse the repository at this point in the history
- Pass `expires_in:` to `write_multi` so the cache key is written with the expiration.
- Added test.
- Added documentation.
  • Loading branch information
jclusso committed Apr 16, 2024
1 parent 64fadc6 commit eddd149
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 1 deletion.
4 changes: 4 additions & 0 deletions actionview/CHANGELOG.md
@@ -1,3 +1,7 @@
* Add `expires_in:` option to `render` when used with `collection:`

*Jarrett Lusso*

* Add queries count to template rendering instrumentation

```
Expand Down
Expand Up @@ -111,7 +111,7 @@ def fetch_or_cache_partial(cached_partials, template, order_by:)
end

unless entries_to_write.empty?
collection_cache.write_multi(entries_to_write)
collection_cache.write_multi(entries_to_write, @options.slice(:expires_in))
end

keyed_partials
Expand Down
11 changes: 11 additions & 0 deletions actionview/test/template/render_test.rb
Expand Up @@ -936,6 +936,17 @@ class CachedCustomer < Customer; end
assert_equal "Hello: david", ActionView::PartialRenderer.collection_cache.read(key)
end

test "template body written to cache with expiration when expires_in set" do
customer = Customer.new("jarrett", 2)
key = cache_key(customer, "test/_customer")
assert_nil ActionView::PartialRenderer.collection_cache.read(key)
@view.render(partial: "test/customer", collection: [customer], cached: true, expires_in: 1.hour)
assert_equal "Hello: jarrett", ActionView::PartialRenderer.collection_cache.read(key)
cache_data = ActionView::PartialRenderer.collection_cache.instance_variable_get('@data')
cache_key = cache_data.detect { |k, _v| k.include?('jarrett') }.last
assert cache_key.expires_at.present?
end

test "collection caching does not cache by default" do
customer = Customer.new("david", 1)
key = cache_key(customer, "test/_customer")
Expand Down
9 changes: 9 additions & 0 deletions guides/source/caching_with_rails.md
Expand Up @@ -132,6 +132,15 @@ do not overwrite each other:
cached: ->(product) { [I18n.locale, product] } %>
```

Additionally, you can configure `expires_in` to explicitly set the expiration.

```html+erb
<%= render partial: 'products/product',
collection: @products,
cached: true,
expires_in: 1.hour %>
```

### Russian Doll Caching

You may want to nest cached fragments inside other cached fragments. This is
Expand Down

0 comments on commit eddd149

Please sign in to comment.