Evgenia Karunus
Evgenia Karunus

Reputation: 11202

Sinatra: page renews results even though I told it to cache previous ones

I follow the example from 'Sinatra: up and running'. Following code:

before  do
 content_type :txt
end

get '/' do
 headers "Cache-Control" => "public, must-revalidate, max-age=3600", 
 "Expires" => Time.at(Time.now.to_i + (60 * 60)).to_s
 "This page rendered at #{Time.now}."
end

is supposed to show the right time once, and renew it only after an hour (because root page gets cached). But it shows right time every time I renew the page in my browser (Opera, Chrome, Firefox). I use Webrick server and shotgun gem. What could be the issue?

edit: I changed the server for thin, but issue is still up there.

Upvotes: 1

Views: 132

Answers (1)

matt
matt

Reputation: 79743

This is the correct behaviour. The page is being cached by your web browser, but when you refresh the page you override this cache and explicitly tell the browser to fetch the page again. If you follow a link to the page rather than refreshing, like you would do when browsing normally, the cached version will be used.

Here’s a little app that should show the difference:

require 'sinatra'

before do
  content_type :html
end

get '/' do
  "<a href=/cached>Cached</a><br><a href=/uncached>Uncached</a>"
end

get '/cached' do
  headers "Cache-Control" => "public, must-revalidate, max-age=3600", 
    "Expires" => Time.at(Time.now.to_i + (60 * 60)).to_s
  "<p>This page rendered at #{Time.now}.<p><a href=/>Back</a>"
end

get '/uncached' do
  "<p>This page rendered at #{Time.now}.<p><a href=/>Back</a>"
end

If you run this, browse to the root url and then click the “Cached” link and back the time displayed should remain the same, since the cached version is being used and no requests are being made to the server. If you follow the “Uncached” link and back repeatedly the time displayed will increase each time since the page isn’t being cached and a new request is being made each time.

Upvotes: 2

Related Questions