Class: Rack::Webconsole::Assets

Inherits:
Object
  • Object
show all
Includes:
AssetHelpers
Defined in:
lib/rack/webconsole/assets.rb

Overview

Assets is a Rack middleware responsible for injecting view code for the console to work properly.

It intercepts HTTP requests, detects successful HTML responses and injects HTML, CSS and JavaScript code into those.

Instance Method Summary collapse

Methods included from AssetHelpers

#css_code, #html_code, #js_code, #render

Constructor Details

#initialize(app) ⇒ Assets

Honor the Rack contract by saving the passed Rack application in an ivar.

Parameters:

  • app (Rack::Application)

    the previous Rack application in the middleware chain.



17
18
19
# File 'lib/rack/webconsole/assets.rb', line 17

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object

Checks for successful HTML responses and injects HTML, CSS and JavaScript code into them.

Parameters:

  • env (Hash)

    a Rack request environment.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rack/webconsole/assets.rb', line 25

def call(env)
  status, headers, response = @app.call(env)
  return [status, headers, response] unless check_html?(headers, response) && status == 200

  response_body = full_body(response)

  # Regenerate the security token
  Webconsole::Repl.reset_token

  # Expose the request object to the Repl
  Webconsole::Repl.request = Rack::Request.new(env)

  # Inject the html, css and js code to the view
  response_body.gsub!('</body>', "#{code(env)}</body>")

  headers['Content-Length'] = response_body.bytesize.to_s

  [status, headers, [response_body]]
end

#code(env) ⇒ String

Returns a string with all the HTML, CSS and JavaScript code needed for the view.

It puts the security token inside the JavaScript to make AJAX calls secure.

Returns:

  • (String)

    the injectable code.



52
53
54
55
56
57
58
59
# File 'lib/rack/webconsole/assets.rb', line 52

def code(env)
  html_code <<
    css_code <<
    render(js_code,
           :TOKEN => Webconsole::Repl.token,
           :KEY_CODE => Webconsole.key_code,
           :CONTEXT => env['SCRIPT_NAME'] || "")
end