4.15.0
-
Add experimental caching support, opt-in per component via
include ViewComponent::ExperimentallyCacheable.Components have never participated in Rails' template digests, so a
<% cache %>block wrappingrender MyComponent.newwas never invalidated when the component changed (#234, open since 2020).Including the module registers the component with Rails' own
ActionView::Digestor, so fragment caches are invalidated when the component's template, Ruby class, sidecar files, superclasses, child components, or rendered partials change. This includes components and partials rendered from inline templates and#callmethods. Addingcache_oncaches the component's own rendered output, optionally guarded byif:/unless:, and.cache_digestexposes the digest for use outside a request.class MessageComponent < ViewComponent::Base include ViewComponent::ExperimentallyCacheable cache_on :message, unless: -> { message.draft? } def initialize(message:) @message = message end end
This API is experimental and may change or be removed in a non-major release. It's shipping opt-in and per-component precisely so we can iterate on it in response to real-world use. Please try it and tell us what breaks, what's missing, and what feels wrong in #234. We're especially interested in feedback on: whether
cache_onis the right shape for declaring cache keys, how the feature behaves with slots and content blocks, and whether the# Template Dependency:escape hatch is sufficient for dynamic renders. See the caching guide for details and known caveats.This work builds directly on prior art from the community. The
cache_onAPI and the case for component-local caching come from #2126 by Reegan Viljoen. The approach of integrating with Rails' digest tree rather than reimplementing it comes fromview_component-cache_digestby Godfrey Chan. The invalidation cases it's tested against were contributed by JWShuff and timburgan, drawing onview_component-fragment_cachingby Patrick Arnett. The issue was opened and researched by ozzyaaron, pinzonjulian, and Derek Kniffin, and the digest workaround that surfaced the superclass gap came from cannikin and rnestler. Cache-key correctness issues (formats sharing an entry, positionalnilcollisions, conditional caching, and ignoredcache_onblocks) were found and reported by Reegan Viljoen.Reegan Viljoen, Godfrey Chan, JWShuff, timburgan, Patrick Arnett, ozzyaaron, pinzonjulian, Derek Kniffin, cannikin, rnestler, Joel Hawksley