-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebug_logger.rb
58 lines (51 loc) · 1.17 KB
/
firebug_logger.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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