How to use etag in Sinatra

829 views
Skip to first unread message

KD

unread,
Sep 14, 2009, 5:00:32 PM9/14/09
to rack-cache
HTTP Caching was new to me (as was most of this stack), but I was able
to quickly get rack:cache working in my Sinatra app with the response
["Cache-Control"] = "max-age=30, public". Unfortunately, my
underlying content can change quite a bit via other means and the
hardcoded max-age simply doesn't cut it when my page content must
reflect the change.

It looks like etag might be an answer, but I can't find much doc on
its usage in sinatra. In my sinatra route I tried:

get '/someroute' do
etag "foo"
erb :someview
end

I guessed i thought the above would halt prior to the erb line when
accessed following the initial call. Of course, I wouldn't hardcode
the etag value in real code.

Is there any documentation that would explain how to use this in
Sinatra?

Thanks.

Ryan Tomayko

unread,
Sep 15, 2009, 5:56:32 PM9/15/09
to rack-...@googlegroups.com
On Mon, Sep 14, 2009 at 2:00 PM, KD <inbo...@gmail.com> wrote:
> HTTP Caching was new to me (as was most of this stack), but I was able
> to quickly get rack:cache working in my Sinatra app with the response
> ["Cache-Control"] = "max-age=30, public".   Unfortunately, my
> underlying content can change quite a bit via other means and the
> hardcoded max-age simply doesn't cut it when my page content must
> reflect the change.
>
> It looks like etag might be an answer, but I can't find much doc on
> its usage in sinatra.  In my sinatra route I tried:
>
> get '/someroute' do
>  etag "foo"
>  erb :someview
> end
>
> I guessed i thought the above would halt prior to the erb line when
> accessed following the initial call.  Of course, I wouldn't hardcode
> the etag value in real code.

That's exactly how etag works in Sinatra. When the If-None-Match
request header matches the ETag provided, the route is halted with 304
Not Modified response. Rack::Cache will serve the response from cache
for another 30s afterward. You can also set the Cache-Control header
here to extend the life of the cache further. e.g.,

get '/someroute' do
response['Cache-Control'] = 'public, max-age=3600'


etag 'foo'
erb :someview
end

Are you seeing different behavior?

Thanks,
Ryan

KD

unread,
Sep 16, 2009, 7:29:40 AM9/16/09
to rack-cache
No, it always drops through to the erb :someview. Perhaps my ajax
requests need to manually add the if-none-match header?

KD

unread,
Sep 16, 2009, 10:58:23 AM9/16/09
to rack-cache
This appears to have been due to an older release of JQUERY, for which
Etag support was recently added.
Reply all
Reply to author
Forward
0 new messages