Skip to content
This repository has been archived by the owner on Oct 20, 2020. It is now read-only.

Commit

Permalink
smarter Last-Modified header based on template mtime
Browse files Browse the repository at this point in the history
  • Loading branch information
mislav committed May 16, 2012
1 parent 73a5042 commit 9aeb37d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
14 changes: 7 additions & 7 deletions app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ def page_title title = nil
end
end

require_relative 'lib/auto_last_modified'

before do
page_title "Pretty RFC"
end
Expand All @@ -112,9 +114,8 @@ def page_title title = nil
end

get "/" do
cache_control :public
last_modified File.mtime('views/index.erb')
erb :index
expires 5 * 60, :public
erb :index, auto_last_modified: true
end

get "/search" do
Expand All @@ -131,12 +132,11 @@ def page_title title = nil
end

get "/:doc_id" do
expires 5 * 60, :public

@rfc = RfcDocument.fetch(params[:doc_id]) { not_found }
redirect to(@rfc.id) unless request.path == "/#{@rfc.id}"

cache_control :public
last_modified @rfc.last_modified

@rfc.make_pretty href_resolver
erb :show
erb :show, auto_last_modified: @rfc.last_modified
end
35 changes: 35 additions & 0 deletions lib/auto_last_modified.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
require 'sinatra/base'

# Adds functionality to template rendering methods to call last_modified with
# the template's timestamp before actually rendering it.
#
# Examples
#
# erb :index, auto_last_modified: true
#
# # with extra timestamp:
# erb :show, auto_last_modified: @item.updated_at
module AutoLastModified
module TiltExt
def mtime
@mtime ||= File.mtime file
end
end

module SinatraExt
private
def compile_template(engine, data, options, views)
set_mtime = options.delete :auto_last_modified
template = super
if set_mtime
mtime = template.mtime
mtime = set_mtime if set_mtime.respond_to? :hour and set_mtime > mtime
last_modified mtime
end
template
end
end

Tilt::Template.send :include, TiltExt
Sinatra::Base.send :include, SinatraExt
end

0 comments on commit 9aeb37d

Please sign in to comment.