Class: ScriptRelocator::Rack
- Inherits:
-
Object
- Object
- ScriptRelocator::Rack
- Defined in:
- lib/script_relocator.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ Rack
constructor
A new instance of Rack.
Constructor Details
#initialize(app) ⇒ Rack
Returns a new instance of Rack.
5 6 7 |
# File 'lib/script_relocator.rb', line 5 def initialize(app) @app = app end |
Instance Method Details
#call(env) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/script_relocator.rb', line 9 def call(env) status, headers, response = @app.call(env) if headers['Content-Type'] !~ %r{^text/html} return status, headers, response end response_body = '' response.each { |part| response_body << part } return status, headers, response unless response_body =~ /\A<!DOCTYPE/ doc = Nokogiri::HTML(response_body) target = doc.at('body') scripts = doc.css('script') return status, headers, response if scripts.empty? scripts.each do |s| next if s['async'] == 'async' || s['defer'] == 'defer' s['data-turbolinks-eval'] = 'false' if s.parent.name == 'head' s.remove target << s end transformed_body = doc.to_html(save_with: Nokogiri::XML::Node::SaveOptions::NO_DECLARATION | Nokogiri::XML::Node::SaveOptions::NO_EMPTY_TAGS | Nokogiri::XML::Node::SaveOptions::AS_HTML) if headers.key?('Content-Length') && headers['Content-Length'].to_i != transformed_body.length headers['Content-Length'] = transformed_body.length.to_s end return status, headers, [transformed_body] end |