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

Constructor Details

- (Assets) initialize(app)

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

- (Object) call(env)

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
# 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

  if response.respond_to?(:body)
    response_body = response.body
  else
    response_body = response.first
  end

  # Inject the html, css and js code to the view
  response_body.gsub!('</body>', "#{code}</body>")
  headers['Content-Length'] = (response_body.length + 2).to_s

  [status, headers, [response_body]]
end

- (String) code

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

Returns:

  • (String)

    the injectable code.



46
47
48
# File 'lib/rack/webconsole/assets.rb', line 46

def code
  html_code << css_code << js_code
end