Skip to content
Edit this page View source of this page

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:

# Gemfile
gem "mankai-cache"

Install the bundle:

bundle install

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.

  1. Include the cache helper in app/views/helpers.rb:

    # app/views/helpers.rb
    module Bookshelf
      module Views
        module Helpers
          include Mankai::Cache::ViewHelpers
        end
      end
    end
    
  2. Add the cache to the view context in app/views/context.rb. The helper reads the cache from the view context:

    # app/views/context.rb
    module Bookshelf
      module Views
        class Context < Hanami::View::Context
          include Deps["cache"]
        end
      end
    end
    

Step 4: Add a page

  1. Generate an action, with its view and template:

    bundle exec hanami generate action clock.show
    

    The command creates app/actions/clock/show.rb, app/views/clock/show.rb, and app/templates/clock/show.html.erb, and adds a route to config/routes.rb.

  2. In config/routes.rb, make sure that the route reads as follows. The generator adds "/clock/:id" for a show action, so change it to "/clock":

    get "/clock", to: "clock.show"
    
  3. Replace the contents of app/views/clock/show.rb with a view that exposes a time that changes on every request:

    # app/views/clock/show.rb
    module Bookshelf
      module Views
        module Clock
          class Show < Bookshelf::View
            expose(:rendered_at) { Time.now.utc.strftime("%H:%M:%S.%L") }
          end
        end
      end
    end
    

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

  1. Start the app:

    bin/dev
    
  2. Open http://localhost:2300/clock. The cached and rendered times match, because the first request stores the fragment.

  3. 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.
  4. 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.

  1. 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
    end
    

    cache.fetch runs the block only on a miss, stores the result for 10 minutes, and returns it. The block returns a Hash of plain data, because the cache stores a serialized copy of the value.

  2. In app/views/clock/show.rb, expose the report to the template. Add the following line after the rendered_at exposure:

    expose :report
    
  3. Add the following line to the end of app/templates/clock/show.html.erb:

    <p>Report built at <%= report["built_at"] %></p>
    
  4. Reload /clock twice. The first request takes about a second, and the server log shows Building 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.

  1. In a second terminal, start the Hanami console:

    bundle exec hanami console
    
  2. Delete the report's entry:

    Hanami.app["cache"].delete("clock/report")
    # => true
    

    The console uses the same file store as the server, so it deletes the entry that the server wrote.

  3. Reload /clock. The request takes about a second again, the log shows Building 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 :marshal serializer 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, and fresh) 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