Fragment caching helps speed up your web pages by saving parts of a page so they don't have to be rebuilt every time.
0
0
Fragment caching in Ruby on Rails
Introduction
When a page has parts that change rarely but other parts change often.
When rendering a list of items where each item is expensive to build.
When you want to reduce server load by reusing HTML snippets.
When you want faster page loads for users by avoiding repeated work.
Syntax
Ruby on Rails
<% cache('cache_key') do %>
<!-- content to cache -->
<% end %>Use a unique
cache_key to identify the cached fragment.Rails stores the cached HTML and reuses it until the cache expires or is cleared.
Examples
This caches the navigation menu so it doesn't get rebuilt on every page load.
Ruby on Rails
<% cache('menu') do %>
<nav>
<!-- menu items -->
</nav>
<% end %>This caches a product's HTML using a key that includes the product's id, so each product has its own cache.
Ruby on Rails
<% cache(['product', product.id]) do %>
<div><%= product.name %></div>
<% end %>You can use arrays as keys to create namespaced cache keys that change when the user changes.
Ruby on Rails
<% cache(['user', user, 'profile']) do %> <p><%= user.name %></p> <% end %>
Sample Program
This example caches the product details section so it doesn't get rebuilt every time the product page is viewed. The cache key includes the product id, so each product has its own cache. Expire the cache manually when the product changes.
Ruby on Rails
<!-- app/views/products/show.html.erb -->
<h1>Product Details</h1>
<% cache(['product', @product.id]) do %>
<div>
<h2><%= @product.name %></h2>
<p><%= @product.description %></p>
</div>
<% end %>OutputSuccess
Important Notes
Cache keys should be unique and reflect the content they represent.
When the underlying data changes, you should expire or update the cache to show fresh content.
Fragment caching improves performance but adds complexity in cache management.
Summary
Fragment caching saves parts of a page to speed up rendering.
Use unique keys to cache different parts separately.
Remember to expire caches when data changes to keep content fresh.