Class: Insight::Toolbar

Inherits:
Object
  • Object
show all
Includes:
Logging, Render
Defined in:
lib/insight/toolbar.rb

Constant Summary collapse

MIME_TYPES =
["text/html", "application/xhtml+xml"]

Instance Method Summary collapse

Methods included from Logging

logger

Methods included from Render

#compile, #compile!, #compiled_source, #method_name, #method_name_without_locals, #render_template, #signed_params

Constructor Details

#initialize(app, insight) ⇒ Toolbar

Returns a new instance of Toolbar.



8
9
10
11
12
# File 'lib/insight/toolbar.rb', line 8

def initialize(app, insight)
  @app = app
  @insight = insight
  @request_table = Database::RequestTable.new
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/insight/toolbar.rb', line 14

def call(env)
  @env = env
  status, headers, body = @app.call(@env)

  response = Rack::Response.new(body, status, headers)

  if okay_to_modify?(env, response)
    inject_toolbar(response)
  end

  return response.to_a
end

#inject_toolbar(response) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/insight/toolbar.rb', line 34

def inject_toolbar(response)
  full_body = response.body.join
  full_body.sub! /<\/body>/, render + "</body>"

  response["Content-Length"] = full_body.size.to_s

  # Ensure that browser doesn't cache
  response["Etag"] = ""
  response["Cache-Control"] = "no-cache"

  response.body = [full_body]
end

#okay_to_modify?(env, response) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
31
32
# File 'lib/insight/toolbar.rb', line 27

def okay_to_modify?(env, response)
  req = Rack::Request.new(env)
  content_type, charset = response.content_type.split(";")

  response.ok? && MIME_TYPES.include?(content_type) && !req.xhr?
end

#renderObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/insight/toolbar.rb', line 47

def render
  req_id = (@env['insight.request-id'] || @request_table.last_request_id).to_i
  requests = @request_table.to_a.map do |row|
    { :id => row[0], :method => row[1], :path => row[2] }
  end

  logger.info{ "Injecting toolbar: active panels: #{@insight.panels.map{|pnl| pnl.class.name}.inspect}" }

  headers_fragment = render_template("headers_fragment",
                                     :panels => @insight.panels,
                                     :request_id => req_id)

  current_request_fragment = render_template("request_fragment",
                                             :request_id => req_id,
                                             :requests => requests,
                                             :panels => @insight.panels)
  render_template("toolbar",
                  :request_fragment => current_request_fragment,
                  :headers_fragment => headers_fragment,
                  :request_id => req_id)
end