Class: Rack::Toolbar

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/toolbar.rb,
lib/rack/toolbar/version.rb

Constant Summary collapse

CONTENT_TYPE_REGEX =
/text\/html|application\/xhtml\+xml/
INSERTION_METHOD =

alternatively :after

:before
INSERTION_POINT =

alternatively “<body>” to have injection at the top of the body, or whatever else floats your boat.

"</body>"
SNIPPET =
<<EOS
  <h1>Welcome to rack-toolbar</h1>
  <ul>
    <li>Define render in Middleware subclass of Rack::Toolbar to return an HTML snippet.</li>
    <li>or</li>
    <li>Pass an HTML snippet as an argument and use Rack::Toolbar directly: Rack::Toolbar.new(snippet).</li>
    <li>or</li>
    <li>Redefine Rack::Toolbar::SNIPPET and ignore with the warnings.</li>
  </ul>
EOS
VERSION =
"0.1.1"

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Toolbar

Returns a new instance of Toolbar.



22
23
24
25
26
27
28
# File 'lib/rack/toolbar.rb', line 22

def initialize(app, options = {})
  @app = app
  @options = options || {}
  @options[:snippet] ||= self.class::SNIPPET
  @options[:insertion_point] ||= self.class::INSERTION_POINT
  @options[:insertion_method] ||= self.class::INSERTION_METHOD
end

Instance Method Details

#call(env) ⇒ Object



30
31
32
33
34
# File 'lib/rack/toolbar.rb', line 30

def call(env)
  @env = env
  @status, @headers, @response = @app.call(@env)
  [@status, @headers, self]
end

#each(&block) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rack/toolbar.rb', line 42

def each(&block)
  if okay_to_modify?
    body = @response.inject("") do |memo, part|
      memo << part
      memo
    end
    index = body.rindex(@options[:insertion_point])
    if index
      if @options[:insertion_method] != :before
        index += @options[:insertion_point].length
      end
      body.insert(index, render)
      @headers["Content-Length"] = body.bytesize.to_s
      @response = [body]
    end
  end
  @response.each(&block)
end

#okay_to_modify?Boolean

Subclasses may override this method if they have alternate means of deciding which requests to modify.

Returns:

  • (Boolean)


37
38
39
40
# File 'lib/rack/toolbar.rb', line 37

def okay_to_modify?
  return false unless @headers["Content-Type"] =~ self.class::CONTENT_TYPE_REGEX
  true
end

#renderObject



61
62
63
# File 'lib/rack/toolbar.rb', line 61

def render
  @options[:snippet]
end