Created
September 2, 2011 15:00
-
-
Save brentertz/1188842 to your computer and use it in GitHub Desktop.
heroku_rack - static asset middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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