Class: Rack::MiniProfiler
- Inherits:
-
Object
- Object
- Rack::MiniProfiler
- Extended by:
- ProfilingMethods
- Defined in:
- lib/mini_profiler/config.rb,
lib/mini_profiler/version.rb,
lib/mini_profiler/profiler.rb,
lib/patches/db/activerecord.rb,
lib/mini_profiler/asset_version.rb,
lib/mini_profiler/client_settings.rb,
lib/mini_profiler/timer_struct/sql.rb,
lib/mini_profiler/profiling_methods.rb,
lib/mini_profiler/timer_struct/base.rb,
lib/mini_profiler/timer_struct/page.rb,
lib/mini_profiler/storage/file_store.rb,
lib/mini_profiler/storage/redis_store.rb,
lib/mini_profiler/timer_struct/client.rb,
lib/mini_profiler/timer_struct/custom.rb,
lib/mini_profiler/storage/memory_store.rb,
lib/mini_profiler/timer_struct/request.rb,
lib/mini_profiler/storage/abstract_store.rb,
lib/mini_profiler/storage/memcache_store.rb
Defined Under Namespace
Modules: ActiveRecordInstrumentation, ProfilingMethods, TimerStruct Classes: AbstractStore, ClientSettings, Config, Context, FileStore, GCProfiler, MemcacheStore, MemoryStore, NoBrainerProfiler, RedisStore
Constant Summary collapse
- VERSION =
'1.0.0'
- ASSET_VERSION =
'251162ee7dc30da30d5370581c664510'.freeze
Class Method Summary collapse
- .authorize_request ⇒ Object
-
.config ⇒ Object
So we can change the configuration if we want.
- .create_current(env = {}, options = {}) ⇒ Object
- .current ⇒ Object
- .current=(c) ⇒ Object
- .deauthorize_request ⇒ Object
-
.discard_results ⇒ Object
discard existing results, don’t track this request.
- .generate_id ⇒ Object
- .request_authorized? ⇒ Boolean
- .reset_config ⇒ Object
- .resources_root ⇒ Object
- .share_template ⇒ Object
Instance Method Summary collapse
- #analyze_memory ⇒ Object
- #call(env) ⇒ Object
-
#cancel_auto_inject(env) ⇒ Object
cancels automatic injection of profile script for the current page.
- #config ⇒ Object
- #current ⇒ Object
- #current=(c) ⇒ Object
- #dump_env(env) ⇒ Object
- #dump_exceptions(exceptions) ⇒ Object
- #flamegraph(graph) ⇒ Object
- #generate_html(page_struct, env, result_json = page_struct.to_json) ⇒ Object
-
#get_profile_script(env) ⇒ Object
get_profile_script returns script to be injected inside current html page By default, profile_script is appended to the end of all html requests automatically.
- #help(client_settings, env) ⇒ Object
- #ids(env) ⇒ Object
- #ids_comma_separated(env) ⇒ Object
- #ids_json(env) ⇒ Object
-
#initialize(app, config = nil) ⇒ MiniProfiler
constructor
options: :auto_inject - should script be automatically injected on every html page (not xhr).
- #inject(fragment, script) ⇒ Object
- #inject_profiler(env, status, headers, body) ⇒ Object
- #make_link(postfix, env) ⇒ Object
- #serve_html(env) ⇒ Object
- #serve_results(env) ⇒ Object
- #text_result(body) ⇒ Object
- #trim_strings(strings, max_size) ⇒ Object
- #user(env) ⇒ Object
Methods included from ProfilingMethods
counter, counter_method, finish_step, profile_method, profile_singleton_method, record_sql, start_step, step, uncounter_method, unprofile_method, unprofile_singleton_method
Constructor Details
#initialize(app, config = nil) ⇒ MiniProfiler
options: :auto_inject - should script be automatically injected on every html page (not xhr)
70 71 72 73 74 75 76 77 78 79 |
# File 'lib/mini_profiler/profiler.rb', line 70 def initialize(app, config = nil) MiniProfiler.config.merge!(config) @config = MiniProfiler.config @app = app @config.base_url_path << "/" unless @config.base_url_path.end_with? "/" unless @config.storage_instance @config.storage_instance = @config.storage.new(@config.) end @storage = @config.storage_instance end |
Class Method Details
.authorize_request ⇒ Object
53 54 55 |
# File 'lib/mini_profiler/profiler.rb', line 53 def Thread.current[:mp_authorized] = true end |
.config ⇒ Object
So we can change the configuration if we want
18 19 20 |
# File 'lib/mini_profiler/profiler.rb', line 18 def config @config ||= Config.default end |
.create_current(env = {}, options = {}) ⇒ Object
44 45 46 47 48 49 50 51 |
# File 'lib/mini_profiler/profiler.rb', line 44 def create_current(env={}, ={}) # profiling the request context = Context.new context.inject_js = config.auto_inject && (!env['HTTP_X_REQUESTED_WITH'].eql? 'XMLHttpRequest') context.page_struct = TimerStruct::Page.new(env) context.current_timer = context.page_struct[:root] self.current = context end |
.current ⇒ Object
30 31 32 |
# File 'lib/mini_profiler/profiler.rb', line 30 def current Thread.current[:mini_profiler_private] end |
.current=(c) ⇒ Object
34 35 36 37 |
# File 'lib/mini_profiler/profiler.rb', line 34 def current=(c) # we use TLS cause we need access to this from sql blocks and code blocks that have no access to env Thread.current[:mini_profiler_private] = c end |
.deauthorize_request ⇒ Object
57 58 59 |
# File 'lib/mini_profiler/profiler.rb', line 57 def Thread.current[:mp_authorized] = nil end |
.discard_results ⇒ Object
discard existing results, don’t track this request
40 41 42 |
# File 'lib/mini_profiler/profiler.rb', line 40 def discard_results self.current.discard = true if current end |
.generate_id ⇒ Object
9 10 11 |
# File 'lib/mini_profiler/profiler.rb', line 9 def generate_id rand(36**20).to_s(36) end |
.request_authorized? ⇒ Boolean
61 62 63 |
# File 'lib/mini_profiler/profiler.rb', line 61 def Thread.current[:mp_authorized] end |
.reset_config ⇒ Object
13 14 15 |
# File 'lib/mini_profiler/profiler.rb', line 13 def reset_config @config = Config.default end |
.resources_root ⇒ Object
22 23 24 |
# File 'lib/mini_profiler/profiler.rb', line 22 def resources_root @resources_root ||= ::File.("../../html", __FILE__) end |
.share_template ⇒ Object
26 27 28 |
# File 'lib/mini_profiler/profiler.rb', line 26 def share_template @share_template ||= ERB.new(::File.read(::File.("../html/share.html", ::File.dirname(__FILE__)))) end |
Instance Method Details
#analyze_memory ⇒ Object
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'lib/mini_profiler/profiler.rb', line 457 def analyze_memory require 'objspace' utf8 = "utf-8" GC.start trunc = lambda do |str| str = str.length > 200 ? str : str[0..200] if str.encoding != Encoding::UTF_8 str = str.dup str.force_encoding(utf8) unless str.valid_encoding? # work around bust string with a double conversion str.encode!("utf-16","utf-8",:invalid => :replace) str.encode!("utf-8","utf-16") end end str end body = "ObjectSpace stats:\n\n".dup counts = ObjectSpace.count_objects total_strings = counts[:T_STRING] body << counts .sort{|a,b| b[1] <=> a[1]} .map{|k,v| "#{k}: #{v}"} .join("\n") strings = [] string_counts = Hash.new(0) sample_strings = [] max_size = 1000 sample_every = total_strings / max_size i = 0 ObjectSpace.each_object(String) do |str| i += 1 string_counts[str] += 1 strings << [trunc.call(str), str.length] sample_strings << [trunc.call(str), str.length] if i % sample_every == 0 if strings.length > max_size * 2 trim_strings(strings, max_size) end end trim_strings(strings, max_size) body << "\n\n\n1000 Largest strings:\n\n" body << strings.map{|s,len| "#{s[0..1000]}\n(len: #{len})\n\n"}.join("\n") body << "\n\n\n1000 Sample strings:\n\n" body << sample_strings.map{|s,len| "#{s[0..1000]}\n(len: #{len})\n\n"}.join("\n") body << "\n\n\n1000 Most common strings:\n\n" body << string_counts.sort{|a,b| b[1] <=> a[1]}[0..max_size].map{|s,len| "#{trunc.call(s)}\n(x #{len})\n\n"}.join("\n") text_result(body) end |
#call(env) ⇒ Object
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/mini_profiler/profiler.rb', line 153 def call(env) start = Process.clock_gettime(Process::CLOCK_MONOTONIC) client_settings = ClientSettings.new(env, @storage, start) MiniProfiler. if @config. == :whitelist status = headers = body = nil query_string = env['QUERY_STRING'] path = env['PATH_INFO'].sub('//', '/') # Someone (e.g. Rails engine) could change the SCRIPT_NAME so we save it env['RACK_MINI_PROFILER_ORIGINAL_SCRIPT_NAME'] = ENV['PASSENGER_BASE_URI'] || env['SCRIPT_NAME'] skip_it = (@config. && !@config..call(env)) || (@config.skip_paths && @config.skip_paths.any?{ |p| path.start_with?(p) }) || query_string =~ /pp=skip/ if skip_it || ( @config. == :whitelist && !client_settings. ) return client_settings.(@app.call(env)) end # handle all /mini-profiler requests here return client_settings.(serve_html(env)) if path.start_with? @config.base_url_path = client_settings.disable_profiling? # manual session disable / enable if query_string =~ /pp=disable/ || skip_it = true end if query_string =~ /pp=enable/ skip_it = false config.enabled = true end if skip_it || !config.enabled status,headers,body = @app.call(env) client_settings.disable_profiling = true return client_settings.([status,headers,body]) else client_settings.disable_profiling = false end # profile gc if query_string =~ /pp=profile-gc/ current.measure = false if current return client_settings.(Rack::MiniProfiler::GCProfiler.new.profile_gc(@app, env)) end # profile memory if query_string =~ /pp=profile-memory/ query_params = Rack::Utils.parse_nested_query(query_string) = { :ignore_files => query_params['memory_profiler_ignore_files'], :allow_files => query_params['memory_profiler_allow_files'], } [:top]= Integer(query_params['memory_profiler_top']) if query_params.key?('memory_profiler_top') result = StringIO.new report = MemoryProfiler.report() do _,_,body = @app.call(env) body.close if body.respond_to? :close end report.pretty_print(result) return client_settings.(text_result(result.string)) end MiniProfiler.create_current(env, @config) if query_string =~ /pp=normal-backtrace/ client_settings.backtrace_level = ClientSettings::BACKTRACE_DEFAULT elsif query_string =~ /pp=no-backtrace/ current.skip_backtrace = true client_settings.backtrace_level = ClientSettings::BACKTRACE_NONE elsif query_string =~ /pp=full-backtrace/ || client_settings.backtrace_full? current.full_backtrace = true client_settings.backtrace_level = ClientSettings::BACKTRACE_FULL elsif client_settings.backtrace_none? current.skip_backtrace = true end flamegraph = nil trace_exceptions = query_string =~ /pp=trace-exceptions/ && defined? TracePoint status, headers, body, exceptions,trace = nil if trace_exceptions exceptions = [] trace = TracePoint.new(:raise) do |tp| exceptions << tp.raised_exception end trace.enable end begin # Strip all the caching headers so we don't get 304s back # This solves a very annoying bug where rack mini profiler never shows up if config.disable_caching env['HTTP_IF_MODIFIED_SINCE'] = '' env['HTTP_IF_NONE_MATCH'] = '' end orig_accept_encoding = env['HTTP_ACCEPT_ENCODING'] # Prevent response body from being compressed env['HTTP_ACCEPT_ENCODING'] = 'identity' if config.suppress_encoding if query_string =~ /pp=flamegraph/ unless defined?(Flamegraph) && Flamegraph.respond_to?(:generate) flamegraph = "Please install the flamegraph gem and require it: add gem 'flamegraph' to your Gemfile" status,headers,body = @app.call(env) else # do not sully our profile with mini profiler timings current.measure = false match_data = query_string.match(/flamegraph_sample_rate=([\d\.]+)/) mode = query_string =~ /mode=c/ ? :c : :ruby if match_data && !match_data[1].to_f.zero? sample_rate = match_data[1].to_f else sample_rate = config.flamegraph_sample_rate end flamegraph = Flamegraph.generate(nil, :fidelity => sample_rate, :embed_resources => query_string =~ /embed/, :mode => mode) do status,headers,body = @app.call(env) end end else status,headers,body = @app.call(env) end ensure trace.disable if trace env['HTTP_ACCEPT_ENCODING'] = orig_accept_encoding if config.suppress_encoding end skip_it = current.discard if (config. == :whitelist && !MiniProfiler.) skip_it = true end return client_settings.([status,headers,body]) if skip_it # we must do this here, otherwise current[:discard] is not being properly treated if trace_exceptions body.close if body.respond_to? :close query_params = Rack::Utils.parse_nested_query(query_string) trace_exceptions_filter = query_params['trace_exceptions_filter'] if trace_exceptions_filter trace_exceptions_regex = Regexp.new(trace_exceptions_filter) exceptions.reject! { |ex| ex.class.name =~ trace_exceptions_regex } end return client_settings.(dump_exceptions exceptions) end if query_string =~ /pp=env/ && !config.disable_env_dump body.close if body.respond_to? :close return client_settings.(dump_env env) end if query_string =~ /pp=analyze-memory/ body.close if body.respond_to? :close return client_settings.(analyze_memory) end if query_string =~ /pp=help/ body.close if body.respond_to? :close return client_settings.(help(client_settings, env)) end page_struct = current.page_struct page_struct[:user] = user(env) page_struct[:root].record_time((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000) if flamegraph body.close if body.respond_to? :close return client_settings.(self.flamegraph(flamegraph)) end begin @storage.save(page_struct) # no matter what it is, it should be unviewed, otherwise we will miss POST @storage.set_unviewed(page_struct[:user], page_struct[:id]) # inject headers, script if status >= 200 && status < 300 result = inject_profiler(env,status,headers,body) return client_settings.(result) if result end rescue Exception => e if @config.storage_failure != nil @config.storage_failure.call(e) end end client_settings.([status, headers, body]) ensure # Make sure this always happens self.current = nil end |
#cancel_auto_inject(env) ⇒ Object
cancels automatic injection of profile script for the current page
630 631 632 |
# File 'lib/mini_profiler/profiler.rb', line 630 def cancel_auto_inject(env) current.inject_js = false end |
#config ⇒ Object
148 149 150 |
# File 'lib/mini_profiler/profiler.rb', line 148 def config @config end |
#current ⇒ Object
139 140 141 |
# File 'lib/mini_profiler/profiler.rb', line 139 def current MiniProfiler.current end |
#current=(c) ⇒ Object
143 144 145 |
# File 'lib/mini_profiler/profiler.rb', line 143 def current=(c) MiniProfiler.current = c end |
#dump_env(env) ⇒ Object
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 |
# File 'lib/mini_profiler/profiler.rb', line 429 def dump_env(env) body = "Rack Environment\n---------------\n".dup env.each do |k,v| body << "#{k}: #{v}\n" end body << "\n\nEnvironment\n---------------\n" ENV.each do |k,v| body << "#{k}: #{v}\n" end body << "\n\nRuby Version\n---------------\n" body << "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL}\n" body << "\n\nInternals\n---------------\n" body << "Storage Provider #{config.storage_instance}\n" body << "User #{user(env)}\n" body << config.storage_instance.diagnostics(user(env)) rescue "no diagnostics implemented for storage" text_result(body) end |
#dump_exceptions(exceptions) ⇒ Object
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 |
# File 'lib/mini_profiler/profiler.rb', line 411 def dump_exceptions(exceptions) body = "Exceptions raised during request\n\n".dup if exceptions.empty? body << "No exceptions raised" else body << "Exceptions: (#{exceptions.size} total)\n" exceptions.group_by(&:class).each do |klass, exceptions_per_class| body << " #{klass.name} (#{exceptions_per_class.size})\n" end body << "\nBacktraces\n" exceptions.each_with_index do |e, i| body << "##{i+1}: #{e.class} - \"#{e.}\"\n #{e.backtrace.join("\n ")}\n\n" end end text_result(body) end |
#flamegraph(graph) ⇒ Object
562 563 564 565 |
# File 'lib/mini_profiler/profiler.rb', line 562 def flamegraph(graph) headers = {'Content-Type' => 'text/html'} [200, headers, [graph]] end |
#generate_html(page_struct, env, result_json = page_struct.to_json) ⇒ Object
113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/mini_profiler/profiler.rb', line 113 def generate_html(page_struct, env, result_json = page_struct.to_json) # double-assigning to suppress "assigned but unused variable" warnings path = path = "#{env['RACK_MINI_PROFILER_ORIGINAL_SCRIPT_NAME']}#{@config.base_url_path}" version = version = MiniProfiler::ASSET_VERSION json = json = result_json includes = includes = get_profile_script(env) name = name = page_struct[:name] duration = duration = page_struct.duration_ms.round(1).to_s MiniProfiler.share_template.result(binding) end |
#get_profile_script(env) ⇒ Object
get_profile_script returns script to be injected inside current html page By default, profile_script is appended to the end of all html requests automatically. Calling get_profile_script cancels automatic append for the current page Use it when:
-
you have disabled auto append behaviour throught :auto_inject => false flag
-
you do not want script to be automatically appended for the current page. You can also call cancel_auto_inject
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
# File 'lib/mini_profiler/profiler.rb', line 590 def get_profile_script(env) path = "#{env['RACK_MINI_PROFILER_ORIGINAL_SCRIPT_NAME']}#{@config.base_url_path}" settings = { :path => path, :version => MiniProfiler::ASSET_VERSION, :verticalPosition => @config.vertical_position, :horizontalPosition => @config.horizontal_position, :showTrivial => @config.show_trivial, :showChildren => @config.show_children, :maxTracesToShow => @config.max_traces_to_show, :showControls => @config.show_controls, :authorized => true, :toggleShortcut => @config.toggle_shortcut, :startHidden => @config.start_hidden, :collapseResults => @config.collapse_results, :htmlContainer => @config.html_container } if current && current.page_struct settings[:ids] = ids_comma_separated(env) settings[:currentId] = current.page_struct[:id] else settings[:ids] = [] settings[:currentId] = "" end # TODO : cache this snippet script = IO.read(::File.('../html/profile_handler.js', ::File.dirname(__FILE__))) # replace the variables settings.each do |k,v| regex = Regexp.new("\\{#{k.to_s}\\}") script.gsub!(regex, v.to_s) end current.inject_js = false if current script end |
#help(client_settings, env) ⇒ Object
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
# File 'lib/mini_profiler/profiler.rb', line 533 def help(client_settings, env) headers = {'Content-Type' => 'text/html'} body = "<html><body> <pre style='line-height: 30px; font-size: 16px;'> Append the following to your query string: #{make_link "help", env} : display this screen #{make_link "env", env} : display the rack environment #{make_link "skip", env} : skip mini profiler for this request #{make_link "no-backtrace", env} #{"(*) " if client_settings.backtrace_none?}: don't collect stack traces from all the SQL executed (sticky, use pp=normal-backtrace to enable) #{make_link "normal-backtrace", env} #{"(*) " if client_settings.backtrace_default?}: collect stack traces from all the SQL executed and filter normally #{make_link "full-backtrace", env} #{"(*) " if client_settings.backtrace_full?}: enable full backtraces for SQL executed (use pp=normal-backtrace to disable) #{make_link "disable", env} : disable profiling for this session #{make_link "enable", env} : enable profiling for this session (if previously disabled) #{make_link "profile-gc", env} : perform gc profiling on this request, analyzes ObjectSpace generated by request (ruby 1.9.3 only) #{make_link "profile-memory", env} : requires the memory_profiler gem, new location based report #{make_link "flamegraph", env} : works best on Ruby 2.0, a graph representing sampled activity (requires the flamegraph gem). #{make_link "flamegraph&flamegraph_sample_rate=1", env}: creates a flamegraph with the specified sample rate (in ms). Overrides value set in config #{make_link "flamegraph_embed", env} : works best on Ruby 2.0, a graph representing sampled activity (requires the flamegraph gem), embedded resources for use on an intranet. #{make_link "trace-exceptions", env} : requires Ruby 2.0, will return all the spots where your application raises exceptions #{make_link "analyze-memory", env} : requires Ruby 2.0, will perform basic memory analysis of heap </pre> </body> </html> " [200, headers, [body]] end |
#ids(env) ⇒ Object
567 568 569 570 571 572 573 574 |
# File 'lib/mini_profiler/profiler.rb', line 567 def ids(env) all = ([current.page_struct[:id]] + (@storage.get_unviewed_ids(user(env)) || [])).uniq if all.size > @config.max_traces_to_show all = all[0...@config.max_traces_to_show] @storage.set_all_unviewed(user(env), all) end all end |
#ids_comma_separated(env) ⇒ Object
580 581 582 |
# File 'lib/mini_profiler/profiler.rb', line 580 def ids_comma_separated(env) ids(env).join(",") end |
#ids_json(env) ⇒ Object
576 577 578 |
# File 'lib/mini_profiler/profiler.rb', line 576 def ids_json(env) ::JSON.generate(ids(env)) end |
#inject(fragment, script) ⇒ Object
396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
# File 'lib/mini_profiler/profiler.rb', line 396 def inject(fragment, script) # find explicit or implicit body index = fragment.rindex(/<\/body>/i) || fragment.rindex(/<\/html>/i) if index # if for whatever crazy reason we dont get a utf string, # just force the encoding, no utf in the mp scripts anyway if script.respond_to?(:encoding) && script.respond_to?(:force_encoding) script = script.force_encoding(fragment.encoding) end fragment.insert(index, script) else fragment end end |
#inject_profiler(env, status, headers, body) ⇒ Object
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
# File 'lib/mini_profiler/profiler.rb', line 362 def inject_profiler(env,status,headers,body) # mini profiler is meddling with stuff, we can not cache cause we will get incorrect data # Rack::ETag has already inserted some nonesense in the chain content_type = headers['Content-Type'] if config.disable_caching headers.delete('ETag') headers.delete('Date') end headers['X-MiniProfiler-Original-Cache-Control'] = headers['Cache-Control'] unless headers['Cache-Control'].nil? headers['Cache-Control'] = "#{"no-store, " if config.disable_caching}must-revalidate, private, max-age=0" # inject header if headers.is_a? Hash headers['X-MiniProfiler-Ids'] = ids_json(env) end if current.inject_js && content_type =~ /text\/html/ response = Rack::Response.new([], status, headers) script = self.get_profile_script(env) if String === body response.write inject(body,script) else body.each { |fragment| response.write inject(fragment, script) } end body.close if body.respond_to? :close response.finish else nil end end |
#make_link(postfix, env) ⇒ Object
528 529 530 531 |
# File 'lib/mini_profiler/profiler.rb', line 528 def make_link(postfix, env) link = env["PATH_INFO"] + "?" + env["QUERY_STRING"].sub("pp=help", "pp=#{postfix}") "pp=<a href='#{link}'>#{postfix}</a>" end |
#serve_html(env) ⇒ Object
125 126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/mini_profiler/profiler.rb', line 125 def serve_html(env) path = env['PATH_INFO'].sub('//', '/') file_name = path.sub(@config.base_url_path, '') return serve_results(env) if file_name.eql?('results') resources_env = env.dup resources_env['PATH_INFO'] = file_name rack_file = Rack::File.new(MiniProfiler.resources_root, {'Cache-Control' => 'max-age:86400'}) rack_file.call(resources_env) end |
#serve_results(env) ⇒ Object
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/mini_profiler/profiler.rb', line 85 def serve_results(env) request = Rack::Request.new(env) id = request[:id] page_struct = @storage.load(id) unless page_struct @storage.set_viewed(user(env), id) id = ERB::Util.html_escape(request['id']) user_info = ERB::Util.html_escape(user(env)) return [404, {}, ["Request not found: #{id} - user #{user_info}"]] end unless page_struct[:has_user_viewed] page_struct[:client_timings] = TimerStruct::Client.init_from_form_data(env, page_struct) page_struct[:has_user_viewed] = true @storage.save(page_struct) @storage.set_viewed(user(env), id) end # If we're an XMLHttpRequest, serve up the contents as JSON if request.xhr? result_json = page_struct.to_json [200, { 'Content-Type' => 'application/json'}, [result_json]] else # Otherwise give the HTML back html = generate_html(page_struct, env) [200, {'Content-Type' => 'text/html'}, [html]] end end |
#text_result(body) ⇒ Object
523 524 525 526 |
# File 'lib/mini_profiler/profiler.rb', line 523 def text_result(body) headers = {'Content-Type' => 'text/plain'} [200, headers, [body]] end |
#trim_strings(strings, max_size) ⇒ Object
451 452 453 454 455 |
# File 'lib/mini_profiler/profiler.rb', line 451 def trim_strings(strings, max_size) strings.sort!{|a,b| b[1] <=> a[1]} i = 0 strings.delete_if{|_| (i+=1) > max_size} end |
#user(env) ⇒ Object
81 82 83 |
# File 'lib/mini_profiler/profiler.rb', line 81 def user(env) @config.user_provider.call(env) end |