Class: RailsHttpPreload::Middleware
- Inherits:
-
Object
- Object
- RailsHttpPreload::Middleware
- Defined in:
- lib/rails_http_preload/middleware.rb
Instance Method Summary collapse
-
#already_connected?(request) ⇒ Boolean
If the asset host is equal to the request domain, no need to add.
- #call(env) ⇒ Object
- #config ⇒ Object
- #create_link_header(url) ⇒ Object
- #current_asset_host ⇒ Object
-
#html?(response) ⇒ Boolean
Adding this header to, for example, a JSON response would be pointless TODO: remove from Turbo frame responses too.
-
#initialize(app) ⇒ Middleware
constructor
A new instance of Middleware.
- #preconnect_header(response) ⇒ Object
-
#required?(response, request) ⇒ Boolean
TODO: Should we just add it to every response anyway and let the browser figure it out?.
Constructor Details
#initialize(app) ⇒ Middleware
Returns a new instance of Middleware.
7 8 9 |
# File 'lib/rails_http_preload/middleware.rb', line 7 def initialize(app) @app = app end |
Instance Method Details
#already_connected?(request) ⇒ Boolean
If the asset host is equal to the request domain, no need to add.
36 37 38 |
# File 'lib/rails_http_preload/middleware.rb', line 36 def already_connected?(request) request.base_url == current_asset_host end |
#call(env) ⇒ Object
11 12 13 14 15 16 17 |
# File 'lib/rails_http_preload/middleware.rb', line 11 def call(env) response = @app.call(env) response[1]["Link"] = preconnect_header(response) if required?(response, ActionDispatch::Request.new(env)) response end |
#config ⇒ Object
57 58 59 |
# File 'lib/rails_http_preload/middleware.rb', line 57 def config RailsHttpPreload.config end |
#create_link_header(url) ⇒ Object
53 54 55 |
# File 'lib/rails_http_preload/middleware.rb', line 53 def create_link_header(url) "<#{url}>; rel=preconnect" end |
#current_asset_host ⇒ Object
31 32 33 |
# File 'lib/rails_http_preload/middleware.rb', line 31 def current_asset_host ActionController::Base.helpers.compute_asset_host("", host: config.asset_host) end |
#html?(response) ⇒ Boolean
Adding this header to, for example, a JSON response would be pointless TODO: remove from Turbo frame responses too
27 28 29 |
# File 'lib/rails_http_preload/middleware.rb', line 27 def html?(response) response[1]["Content-Type"].match?("html") end |
#preconnect_header(response) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/rails_http_preload/middleware.rb', line 40 def preconnect_header(response) header = [ current_asset_host, *config.additional_urls ].compact.map { |url| create_link_header(url) }.join(", ") if response[1]["Link"] "#{header}, #{response[1]["Link"]}" else header end end |
#required?(response, request) ⇒ Boolean
TODO: Should we just add it to every response anyway and let the browser figure it out?
21 22 23 |
# File 'lib/rails_http_preload/middleware.rb', line 21 def required?(response, request) config.asset_host.present? && html?(response) && !already_connected?(request) end |