Class: Profiler::Middleware::ProfilerMiddleware
- Inherits:
-
Object
- Object
- Profiler::Middleware::ProfilerMiddleware
- Defined in:
- lib/profiler/middleware/profiler_middleware.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ ProfilerMiddleware
constructor
A new instance of ProfilerMiddleware.
Constructor Details
#initialize(app) ⇒ ProfilerMiddleware
Returns a new instance of ProfilerMiddleware.
10 11 12 |
# File 'lib/profiler/middleware/profiler_middleware.rb', line 10 def initialize(app) @app = app end |
Instance Method Details
#call(env) ⇒ Object
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/profiler/middleware/profiler_middleware.rb', line 14 def call(env) return @app.call(env) unless should_profile?(env) profile = Models::Profile.new(build_request(env)) Profiler::CurrentContext.token = profile.token # Capture request body before app processes it req_body_raw = read_rack_input(env) # Store profile in env for collectors env["profiler.profile"] = profile # Create and subscribe collectors collectors = create_collectors(profile) env["profiler.collectors"] = collectors # Measure memory before memory_before = current_memory if Profiler.configuration.track_memory # Process request status, headers, body = @app.call(env) # Measure memory after if Profiler.configuration.track_memory memory_after = current_memory profile.memory = memory_after - memory_before end # Collect and buffer response body (avoids double-reading by ToolbarInjector) body_content = collect_body(body) body = [body_content] # Finish profile profile.finish(status, headers) # Store request and response bodies profile.set_bodies( request_body: req_body_raw, response_body: body_content, req_content_type: env["CONTENT_TYPE"].to_s, resp_content_type: (headers["content-type"] || headers["Content-Type"]).to_s ) # Collect data from all collectors collectors.each do |collector| begin collector.collect if collector.respond_to?(:collect) profile.(collector) rescue => e warn "Collector #{collector.class} failed: #{e.}" end end # Store profile Profiler.storage.save(profile.token, profile) Profiler::CurrentContext.clear # Add profiler token header headers["X-Profiler-Token"] = profile.token # Inject toolbar if HTML response if html_response?(headers) nonce = env['action_dispatch.content_security_policy_nonce'] body = ToolbarInjector.new(body, profile.token, nonce).inject end [status, headers, body] rescue => e warn "Profiler error: #{e.}\n#{e.backtrace.join("\n")}" @app.call(env) end |