Sha256: a4e8fac03cdb6eed4f30200a4df4003c2202c6debb3faa8eb687e0dccbfd10da

Contents?: true

Size: 1.72 KB

Versions: 6

Compression:

Stored size: 1.72 KB

Contents

# cf) xray-rails : xray/middleware.rb

module CopyTunerClient
  class CopyrayMiddleware
    def initialize(app)
      @app = app
    end

    def call(env)
      status, headers, response = @app.call(env)
      if html_headers?(status, headers) && body = response_body(response)
        body = append_css!(body)
        body = append_js!(body)
        content_length = body.bytesize.to_s
        if ActionDispatch::Response === response
          response.body = [body]
          response.headers['Content-Length'] = content_length
          response.to_a
        else
          headers['Content-Length'] = content_length
          [status, headers, [body]]
        end
      else
        [status, headers, response]
      end
    end

    private

    def helpers
      ActionController::Base.helpers
    end

    def append_css!(html)
      html.sub(/<body[^>]*>/) { "#{$~}\n#{css_tag}" }
    end

    def append_js!(html)
      regexp = if ::Rails.application.config.assets.debug
                 CopyTunerClient.configuration.copyray_js_injection_regexp_for_debug
               else
                 CopyTunerClient.configuration.copyray_js_injection_regexp_for_precompiled
               end
      html.sub(regexp) do
        "#{$~}\n" + helpers.javascript_include_tag(:copyray)
      end
    end

    def css_tag
      helpers.stylesheet_link_tag :copyray
    end

    def file?(headers)
      headers["Content-Transfer-Encoding"] == "binary"
    end

    def html_headers?(status, headers)
      status == 200 &&
      headers['Content-Type'] &&
      headers['Content-Type'].include?('text/html') &&
      !file?(headers)
    end

    def response_body(response)
      body = ''
      response.each { |s| body << s.to_s }
      body
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
copy_tuner_client-0.2.4 lib/copy_tuner_client/copyray_middleware.rb
copy_tuner_client-0.2.3 lib/copy_tuner_client/copyray_middleware.rb
copy_tuner_client-0.2.2 lib/copy_tuner_client/copyray_middleware.rb
copy_tuner_client-0.2.1 lib/copy_tuner_client/copyray_middleware.rb
copy_tuner_client-0.2.0 lib/copy_tuner_client/copyray_middleware.rb
copy_tuner_client-0.1.1.beta19 lib/copy_tuner_client/copyray_middleware.rb