fix for weird last_modified behavior, and duplicative work

fix for issue #180
The api should be passed an object that supports .to_time. If it happens
to be something else, make a best effort to convert it to a time object (such
as if a string is passed in -- which happens in a few of the tests).

Failing conversion, the rescue stanza will result in an http 200
response, which should be a 'safe' thing to do.

Signed-off-by: Konstantin Haase <konstantin.mailinglists@googlemail.com>
This commit is contained in:
elij 2011-02-08 13:40:09 -08:00 committed by Konstantin Haase
parent e16bc71590
commit 869fbb427f
2 changed files with 14 additions and 4 deletions

View File

@ -324,10 +324,17 @@ module Sinatra
# with a '304 Not Modified' response.
def last_modified(time)
return unless time
time = time.to_time if time.respond_to?(:to_time)
time = Time.parse time.strftime('%FT%T%:z') if time.respond_to?(:strftime)
response['Last-Modified'] = time.respond_to?(:httpdate) ? time.httpdate : time.to_s
halt 304 if Time.httpdate(request.env['HTTP_IF_MODIFIED_SINCE']) >= time
if time.respond_to?(:to_time)
time = time.to_time
else
## make a best effort to convert something else to a time object
## if this fails, this should throw an ArgumentError, then the
# rescue will result in an http 200, which should be safe
time = Time.parse(time.to_s).to_time
end
response['Last-Modified'] = time.httpdate
# compare based on seconds since epoch
halt 304 if Time.httpdate(request.env['HTTP_IF_MODIFIED_SINCE']).to_i >= time.to_i
rescue ArgumentError
end

View File

@ -599,6 +599,9 @@ class HelpersTest < Test::Unit::TestCase
get '/compare', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2010 23:43:52 GMT' }
assert_equal 200, status
assert_equal 'foo', body
get '/compare', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2100 23:43:52 GMT' }
assert_equal 304, status
assert_equal '', body
end
end