Skip to content

Instantly share code, notes, and snippets.

@jerodsanto
Forked from simonjefford/firebug_logger.rb
Created December 9, 2009 16:23
Show Gist options
  • Save jerodsanto/252575 to your computer and use it in GitHub Desktop.
Save jerodsanto/252575 to your computer and use it in GitHub Desktop.
Rack::FirebugLogger
module Rack
class FirebugLogger
def initialize(app, options = {})
@app = app
@options = options
end
def call(env)
status, headers, orig_response = @app.call(env)
return [status, headers, orig_response] unless (headers["Content-Type"] =~ /html/ && env['firebug.logs'])
new_response = Rack::Response.new([], status, headers)
js = generate_js(env['firebug.logs'])
if orig_response.body =~ /<body>/
orig_response.each do |line|
line.gsub!("</body>", js + "\n</body>")
new_response.write(line)
end
else
new_response.write(orig_response.body + js)
end
new_response.finish
end
private
def generate_js(logs)
js = ["<script type=\"text/javascript\">"]
start_group(js)
logs.each do |level, log|
level = sanitise_level(level)
log.gsub!('"', '\"')
js << "console.#{level.to_s}(\"#{log}\");"
end
end_group(js)
js << "</script>"
js.join("\n")
end
def start_group(js)
if @options[:group]
js << "console.group(\"#{@options[:group]}\");"
end
end
def sanitise_level(level)
[:info, :debug, :warn, :error].include?(level) ? level : :debug
end
def end_group(js)
if @options[:group]
js << "console.groupEnd();"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment