Michael Durrant
Michael Durrant

Reputation: 96494

How to create Sinatra app with page that reloads with new content not cache

I trying to create a fairly minimal example for templates and teaching.

I create my app.rb file

require 'sinatra'

get '/' do
  "Minimal!__ !_!"
end

My Gemfile just has

source 'https://rubygems.org'

gem 'rspec'
gem 'thin'

I started up Sinatra

$ ruby app.rb 
== Sinatra (v2.0.5) has taken the stage on 4567 for development with backup from Thin
Thin web server (v1.7.2 codename Bachmanity)
Maximum connections set to 1024
Listening on localhost:4567, CTRL+C to stop

and I can visit the page

enter image description here

but when I then change the code the page is cached and the new content doesn't show unless i stop and start the server.

I've read the Sinatra documentation but still can't figure it out.

I've tried adding

set :sessions, false

and

   cache_control :off

to no avail

Upvotes: 2

Views: 1081

Answers (2)

ian
ian

Reputation: 12251

If you were having problems with the cache you could tell the browser not to cache anything:

cache_control :no_cache

You might also add Pragma and Expires to the header:

headers \
  "Pragma"   => "no-cache",
  "Expires" => "0"

and put it all in a before filter:

before do
  cache_control :no_cache
  headers \
    "Pragma"   => "no-cache",
    "Expires" => "0"
end

Or, since you're doing demonstrations, open the browser's inspector and turn off caching. Both Chrome and Firefox have this option.

(OP Adding this) A minimalist version for one call might be just to have

  headers "Expires" => "0"

within the get in question

Upvotes: 2

ashmaroli
ashmaroli

Reputation: 5444

You need to use sinatra-reloader

Based on the example code, your app seems to be of the "classic" type. Therefore simply load the reloader library into your app:

require 'sinatra'
require 'sinatra/reloader' if development?

get '/' do
  "Minimal!__ !_!"
end

Since you're using a Gemfile, ensure that you've the sinatra-contrib gem listed as well (and install it via bundle install):

source 'https://rubygems.org'

gem 'rspec'
gem 'thin'
gem 'sinatra', '~> 2.0`
gem 'sinatra-contrib', '~> 2.0'

Otherwise install the gem directly: gem install sinatra-contrib

Now onwards anytime you start up the server in 'development' mode and make changes to either your app.rb or your views/index.erb, the changes will be reflected in your browser with a refresh.

Upvotes: 1

Related Questions