Cache your first view fragment¶
In this tutorial, you add a cache to a Hanami app, cache part of a page, and confirm that the second request reuses the stored HTML. Then you cache data in an action and delete the stored entry. You don't need experience with cache libraries. Allow about 15 minutes.
The tutorial uses the file store, which keeps entries in the app's tmp/cache directory. Entries
survive code reloads and server restarts, and every process on your machine, including the Hanami
console, sees the same entries.
Before you begin¶
You need a Hanami 3 app that boots with bin/dev. This tutorial doesn't use a database.
Run all commands from the app root. The examples use Bookshelf as the app module; replace it with
your app's module. To see the finished clock page, open /clock in the
demo app.
Step 1: Add the gem¶
Add the cache gem to your Gemfile:
Install the bundle:
Step 2: Register the cache provider¶
Create config/providers/cache.rb. If the config/providers directory doesn't exist, create it
first:
# config/providers/cache.rb
require "mankai/cache"
Hanami.app.register_provider(:cache, from: :mankai_cache) do
configure do |config|
config.store = Hanami.env?(:test) ? :memory : :file
config.expires_in = 3600
end
end
The provider registers the cache as the "cache" component. Development and production use the
file store, and entries expire after one hour unless you pass another lifetime. Tests use the memory
store, which starts empty in each process.
Step 3: Give views the cache¶
Hanami generated app/views/helpers.rb and app/views/context.rb with your app.
-
Include the cache helper in
app/views/helpers.rb: -
Add the cache to the view context in
app/views/context.rb. The helper reads the cache from the view context:
Step 4: Add a page¶
-
Generate an action, with its view and template:
The command creates
app/actions/clock/show.rb,app/views/clock/show.rb, andapp/templates/clock/show.html.erb, and adds a route toconfig/routes.rb. -
In
config/routes.rb, make sure that the route reads as follows. The generator adds"/clock/:id"for ashowaction, so change it to"/clock": -
Replace the contents of
app/views/clock/show.rbwith a view that exposes a time that changes on every request:
Step 5: Cache a view fragment¶
Replace the contents of app/templates/clock/show.html.erb with the following template. It wraps
one paragraph in the cache view helper, with the key "clock" and a lifetime of 60 seconds:
<%# app/templates/clock/show.html.erb %>
<h1>Clock</h1>
<%= cache "clock", expires_in: 60 do %>
<p>Cached at <%= rendered_at %></p>
<% end %>
<p>Rendered at <%= rendered_at %></p>
Step 6: Confirm that the fragment is cached¶
-
Start the app:
-
Open
http://localhost:2300/clock. The cached and rendered times match, because the first request stores the fragment. - Reload the page within a minute. The cached time stays the same, and the rendered time changes. The second request is a hit: it finds the stored fragment and doesn't render it again.
- Wait at least 60 seconds, then reload. The cached time updates and matches the rendered time again, because the entry expired.
Step 7: Cache data in an action¶
The cache isn't only for HTML. In this step, the action builds a report that takes a second to compute, and caches it.
-
Replace the contents of
app/actions/clock/show.rb:# app/actions/clock/show.rb module Bookshelf module Actions module Clock class Show < Bookshelf::Action include Deps["cache", "logger"] def handle(request, response) response[:report] = cache.fetch("clock/report", expires_in: 600) do logger.info("Building the clock report") sleep 1 # Stands in for slow work, such as a database query. {"built_at" => Time.now.utc.strftime("%H:%M:%S")} end end end end end endcache.fetchruns the block only on a miss, stores the result for 10 minutes, and returns it. The block returns aHashof plain data, because the cache stores a serialized copy of the value. -
In
app/views/clock/show.rb, expose the report to the template. Add the following line after therendered_atexposure: -
Add the following line to the end of
app/templates/clock/show.html.erb: -
Reload
/clocktwice. The first request takes about a second, and the server log showsBuilding the clock report. The second request is fast, the log line doesn't appear again, and the report time stays the same.
Step 8: Delete the entry¶
When the data behind an entry changes, delete the entry so that the next request computes it again.
-
In a second terminal, start the Hanami console:
-
Delete the report's entry:
The console uses the same file store as the server, so it deletes the entry that the server wrote.
-
Reload
/clock. The request takes about a second again, the log showsBuilding the clock report, and the report time updates.
Before you cache in production¶
Before you deploy, check the following:
- Don't put one user's private output in a shared key. Include the user or role in the key, or don't cache that fragment.
- Keep the store private to the app. The default
:marshalserializer can create arbitrary Ruby objects from stored data. If anything you don't control can write to the store, use:json. - Make sure that a cache miss still produces a correct result.
- Use HTTP caching (
cache_control,expires, andfresh) for whole responses. - If several servers must share entries, use the SQL store. The file store is shared only by processes on one machine.
What's next¶
- To learn about hits, misses, and stores, read How the cache works.
- To design keys that change with your data and to invalidate entries, see Cache data and views.
- To compare the memory, file, and SQL stores, see Choose a store and serializer.
- To share the cache between servers, see Share the cache with the SQL store.
- For every method and setting, see the mankai-cache reference.