Class: Xray::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/xray/middleware.rb

Overview

This middleware is responsible for injecting xray.js and the Xray bar into the app’s pages. It also listens for requests to open files with the user’s editor.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



11
12
13
# File 'lib/xray/middleware.rb', line 11

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/xray/middleware.rb', line 15

def call(env)
  # Request for opening a file path.
  if env['PATH_INFO'] == OPEN_PATH
    req, res = Rack::Request.new(env), Rack::Response.new
    out, _err, status = Xray.open_file(req.GET['path'])
    if status.success?
      res.status = 200
    else
      res.write out
      res.status = 500
    end
    res.finish
  elsif env['PATH_INFO'] == UPDATE_CONFIG_PATH
    req, res = Rack::Request.new(env), Rack::Response.new
    if req.post? && Xray.config.editor = req.POST['editor']
      res.status = 200
    else
      res.status = 400
    end
    res.finish

  # Inject xray.js and friends if this is a successful HTML response
  else
    status, headers, response = @app.call(env)

    if html_headers?(status, headers) && body = response_body(response)
      if body =~ script_matcher('xray')
        # Inject the xray bar if xray.js is already on the page
        inject_xray_bar!(body)
      elsif Rails.application.config.assets.debug
        # Otherwise try to inject xray.js if assets are unbundled
        if append_js!(body, 'jquery', 'xray')
          inject_xray_bar!(body)
        end
      end

      content_length = body.bytesize.to_s

      # For rails v4.2.0+ compatibility
      if defined?(ActionDispatch::Response::RackBody) && ActionDispatch::Response::RackBody === response
        response = response.instance_variable_get(:@response)
      end

      # Modifying the original response obj maintains compatibility with other middlewares
      if ActionDispatch::Response === response
        response.body = [body]
        response.header['Content-Length'] = content_length unless committed?(response)
        response.to_a
      else
        headers['Content-Length'] = content_length
        [status, headers, [body]]
      end
    else
      [status, headers, response]
    end
  end
end