Skip to content

Instantly share code, notes, and snippets.

@brentertz
Created September 2, 2011 15:00
Show Gist options
  • Save brentertz/1188842 to your computer and use it in GitHub Desktop.
Save brentertz/1188842 to your computer and use it in GitHub Desktop.
heroku_rack - static asset middleware
module Heroku
class StaticAssetsMiddleware
def initialize(app)
@app = app
end
def call(env)
# call returns an array containing [response code, header, Rack::Response]
reply = @app.call(env)
reply = cache_static_asset(reply)
reply
end
def cache_static_asset(reply)
return reply unless can_cache?(reply)
status, headers, response = reply
# static files are cacheable for 12hrs
headers['Cache-Control'] = 'public, max-age=43200'
build_new_reply(status, headers, response)
end
def can_cache?(reply)
response = reply[2]
status = reply[0]
response.kind_of?(Rack::File) and status.to_i == 200
end
def build_new_reply(status, headers, response)
headers.delete('Etag') if headers.has_key?('Etag')
[ status, headers, response ]
end
end
end
# For rails - place this file in an initializer
# Override heroku_rack - StaticAssetsMiddleware to extend default Cache-Control header
# See this thread --> http://groups.google.com/group/heroku/browse_thread/thread/607f0dc9a3979e1b
module Heroku
class StaticAssetsMiddleware
def cache_static_asset(reply)
return reply unless can_cache?(reply)
status, headers, response = reply
# static files are cacheable for ...
headers['Cache-Control'] = 'public, max-age=0'
#headers['Cache-Control'] = 'public, max-age=43200' # 12 hours - Heroku default
#headers['Cache-Control'] = 'public, max-age=31556926' # 1 year
build_new_reply(status, headers, response)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment