2017-04-12 10:52:52 -04:00
|
|
|
# frozen_string_literal: true
|
2013-04-18 02:32:48 -04:00
|
|
|
module Middleware
|
2013-09-10 15:21:07 -04:00
|
|
|
# Cheat and bypass Rails in development mode if the client attempts to download a static asset
|
|
|
|
# that's already been downloaded.
|
|
|
|
#
|
|
|
|
# Also ensures that assets are not cached in development mode. Around Chrome 29, the behavior
|
|
|
|
# of `must-revalidate` changed and would often not request assets that had changed.
|
|
|
|
#
|
|
|
|
# To use, include in your project and add the following to development.rb:
|
|
|
|
#
|
|
|
|
# require 'middleware/turbo_dev'
|
|
|
|
# config.middleware.insert 0, Middleware::TurboDev
|
|
|
|
#
|
2013-04-18 02:32:48 -04:00
|
|
|
class TurboDev
|
|
|
|
def initialize(app, settings = {})
|
|
|
|
@app = app
|
|
|
|
end
|
2013-09-09 15:35:13 -04:00
|
|
|
|
2013-09-10 15:21:07 -04:00
|
|
|
def call(env)
|
2015-03-08 20:45:36 -04:00
|
|
|
root = "#{GlobalSetting.relative_url_root}/assets/"
|
|
|
|
is_asset = env["REQUEST_PATH"] && env["REQUEST_PATH"].starts_with?(root)
|
2013-09-09 15:35:13 -04:00
|
|
|
|
2013-04-18 02:32:48 -04:00
|
|
|
# hack to bypass all middleware if serving assets, a lot faster 4.5 seconds -> 1.5 seconds
|
2013-09-09 15:35:13 -04:00
|
|
|
if (etag = env["HTTP_IF_NONE_MATCH"]) && is_asset
|
2015-03-08 20:45:36 -04:00
|
|
|
name = env["REQUEST_PATH"][(root.length)..-1]
|
2013-04-18 02:32:48 -04:00
|
|
|
etag = etag.gsub "\"", ""
|
|
|
|
asset = Rails.application.assets.find_asset(name)
|
|
|
|
return 304, {}, [] if asset && asset.digest == etag
|
|
|
|
end
|
|
|
|
|
2013-09-09 15:35:13 -04:00
|
|
|
status, headers, response = @app.call(env)
|
|
|
|
headers["Cache-Control"] = "no-cache" if is_asset
|
|
|
|
[status, headers, response]
|
2013-04-18 02:32:48 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|