Created
October 14, 2009 13:20
-
-
Save simonjefford/210069 to your computer and use it in GitHub Desktop.
My CodeRack competition entry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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/ && 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 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 << "</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