What Sinatra example are you referring to here? I'd like to take a
look. I've personally never used before filters to mess with cache
headers.
> I've got a simple flat-file system going for my articles, and lets say
> that I want to cache them for 1 hour unless modified. Obviously this
> is easy to do with File.mtime, but where do I send the headers? I
> *could* use before-do, but I have other routes that need a different
> logic to cache and I'd rather avoid if-then-else and case statements.
>
> If I do,--
>
>> get '/article/:id/ do
>> expires 1.hour # sets response["Expires"] to the httpdate of 1.hour from Time.now
>> last_modified article_mtime(params[:id]) # File.mtime().httpdate...
>> haml :"articles/#{params[:id]}.haml"
>> end
>
> Obviously I'll still generate a HTML response, which might not even
> get sent due to caching.
That's not true, actually. The #last_modified methods exits the route
block immediately with a 304 Not Modified response if the request
includes an If-Modified-Since header that matches the date specified.
Both #last_modified and #etag have this behavior. Sinatra has a "halt"
primitive that uses throw to exit the route block immediate. See the
#last_modfied source for more:
> But how do I know? Can I,--
>
>> get '/article/:id/ do
>> expires 1.hour
>> last_modified article_mtime(params[:id])
>> haml :"articles/#{params[:id]}.haml" unless response.fresh?
>> end
>
> Part of the trouble is that I've got semi-static routes with content
> to be generated every 6/12/24 hours with different reasoning on when
> it was last modified. You can guess how fast before-do will become
> messy...
Does understanding the halting behavior of last_modified and etag
clear this up? I wouldn't suggest using before filters for any of this
stuff.
> In other words, just how do I integrate with Rack::Cache?
Sounds like you're doing just fine :) You might also appreciate the
X-Rack-Cache response header, which you can see easily using a http
monitoring tool like firebug's network panel. The header includes
basic information on how the cache handled the request (whether it was
fresh or stale, validated, etc).
Thanks,
Ryan