Skip to content

Instantly share code, notes, and snippets.

@simonjefford
Created October 14, 2009 13:20
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save simonjefford/210069 to your computer and use it in GitHub Desktop.
Save simonjefford/210069 to your computer and use it in GitHub Desktop.
My CodeRack competition entry
# See also http://github.com/simonjefford/rack_firebug_logger
# for this middleware + tests + a rails plugin
class FirebugLogger
def initialize(app, options = {})
@app = app
@options = options
end
def call(env)
dup._call(env)
end
def _call(env)
status, headers, body = @app.call(env)
return [status, headers, body] unless (headers["Content-Type"] =~ /html/)
return [status, headers, body] unless env['firebug.logs']
response = Rack::Response.new([], status, headers)
js = generate_js(env['firebug.logs'])
body.each do |line|
line.gsub!("</body>", js)
response.write(line)
end
response.finish
end
private
def generate_js(logs)
js = ["<script>"]
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 << "</body>"
js.join("\n")
end
def start_group(js)
if @options[:group]
js << "console.group(\"#{@options[:group]}\");"
end
end
def sanitise_level(level)
if [:info, :debug, :warn, :error].include?(level)
level
else
:debug
end
end
def end_group(js)
if @options[:group]
js << "console.groupEnd();"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment