Skip to content

Commit

Permalink
Added If-Modified-Since handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jbaudanza committed Feb 14, 2011
1 parent fa4db1c commit 2e2d1f1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
17 changes: 14 additions & 3 deletions lib/rack/almost_static.rb
Expand Up @@ -23,8 +23,9 @@ def initialize(app, options={}, &block)
@urls = options[:urls]
end

def response(status, body, content_type='text/plain')
[status, {"Content-Type" => content_type,
def response(status, body)
body += "\r\n"
[status, {"Content-Type" => 'text/plain',
"Content-Length" => body.size.to_s},
[body]]
end
Expand All @@ -39,7 +40,7 @@ def compile(source_file)

def call(env)
request_path = Utils.unescape(env["PATH_INFO"])
return response( 403, "Forbidden: #{request_path}\n" ) if request_path.include? ".."
return response( 403, 'Forbidden') if request_path.include? ".."

urls.each do |url|
match_parts = url.split('/')
Expand All @@ -53,11 +54,21 @@ def call(env)

source_file = F.join(source_dir, request_base)
if F.exists?(source_file)
last_modified_time = F.mtime(source_file)

if env['HTTP_IF_MODIFIED_SINCE']
cached_time = Time.parse(env['HTTP_IF_MODIFIED_SINCE'])
if last_modified_time <= cached_time
return response(304, 'Not modified')
end
end

body = compile(source_file)

headers = {
'Content-Type' => @content_type,
'Content-Length' => body.length.to_s,
'Last-Modified' => last_modified_time.httpdate
}

if @cache_ttl
Expand Down
19 changes: 19 additions & 0 deletions spec/almost_static_spec.rb
Expand Up @@ -59,6 +59,25 @@ def app
last_response.body.should include('Lobstericious')
end

it "should include a last-modified header" do
get '/chickenscripts/application.chickenscript'
last_response.headers["Last-Modified"].should == File.mtime("#{@source_dir}/application.eggscript").httpdate
end

it "should respond with a 304 on a last-modified hit" do
last_modified_time = File.mtime("#{@source_dir}/application.eggscript").httpdate
get '/chickenscripts/application.chickenscript', {}, {'HTTP_IF_MODIFIED_SINCE' => last_modified_time}
last_response.status.should == 304
last_response.body.should == "Not modified\r\n"
end

it "should return the compiled code on a last-modified miss" do
last_modified_time = (File.mtime("#{@source_dir}/application.eggscript") - 10).httpdate
get '/chickenscripts/application.chickenscript', {}, {'HTTP_IF_MODIFIED_SINCE' => last_modified_time}
last_response.status.should == 200
last_response.body.should == "chickenscript"
end

describe "Caching" do
it "should not cache by default" do
@options.delete(:cache)
Expand Down

0 comments on commit 2e2d1f1

Please sign in to comment.