Permalink
Browse files

smarter Last-Modified header based on template mtime

  • Loading branch information...
1 parent 73a5042 commit 9aeb37d462f58d1725ead2c6bab3133e1ea225c4 @mislav committed May 16, 2012
Showing with 42 additions and 7 deletions.
  1. +7 −7 app.rb
  2. +35 −0 lib/auto_last_modified.rb
View
14 app.rb
@@ -93,6 +93,8 @@ def page_title title = nil
end
end
+require_relative 'lib/auto_last_modified'
+
before do
page_title "Pretty RFC"
end
@@ -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
@@ -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
View
35 lib/auto_last_modified.rb
@@ -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.