class RailsMiniProfiler::Badge

Wraps functionality to render an interactive badge on top of HTML responses

@api private

Public Class Methods

new(request_context, configuration: RailsMiniProfiler.configuration) click to toggle source

@param request_context [RequestContext] The current request context @param configuration [Configuration] The current configuration

# File lib/rails_mini_profiler/badge.rb, line 16
def initialize(request_context, configuration: RailsMiniProfiler.configuration)
  @configuration = configuration
  @profiled_request = request_context.profiled_request
  @original_response = request_context.response
end

Public Instance Methods

render() click to toggle source

Inject the badge into the response

@return [ResponseWrapper] The modified response

# File lib/rails_mini_profiler/badge.rb, line 25
def render
  content_type = @original_response.headers['Content-Type']
  return @original_response unless content_type =~ %r{text/html}

  return @original_response unless @configuration.ui.badge_enabled

  modified_response = Rack::Response.new([], @original_response.status, @original_response.headers)
  modified_response.write(modified_body)
  modified_response.finish

  response = @original_response.response
  response.close if response.respond_to?(:close)

  ResponseWrapper.new(@original_response.status,
                      @original_response.headers,
                      modified_response)
end

Private Instance Methods

badge_content() click to toggle source

Render the badge template

@return String The badge HTML content to be injected

# File lib/rails_mini_profiler/badge.rb, line 61
def badge_content
  html = IO.read(File.expand_path('../../app/views/rails_mini_profiler/badge.html.erb', __dir__))
  @position = css_position
  template = ERB.new(html)
  template.result(binding)
end
css_position() click to toggle source

Transform the configuration position into CSS style positions

@return String The badge position as CSS style

# File lib/rails_mini_profiler/badge.rb, line 71
def css_position
  case @configuration.ui.badge_position
  when 'top-right'
    'top: 5px; right: 5px;'
  when 'bottom-left'
    'bottom: 5px; left: 5px;'
  when 'bottom-right'
    'bottom: 5px; right: 5px;'
  else
    'top: 5px; left: 5px;'
  end
end
modified_body() click to toggle source

Modify the body of the original response

@return String The modified body

# File lib/rails_mini_profiler/badge.rb, line 48
def modified_body
  body = @original_response.response.body
  index = body.rindex(%r{</body>}i) || body.rindex(%r{</html>}i)
  if index
    body.dup.insert(index, badge_content)
  else
    body
  end
end