Class: Rack::MiniProfiler

Inherits:
Object
  • Object
show all
Extended by:
ProfilingMethods
Includes:
Actions, Views
Defined in:
lib/mini_profiler.rb,
lib/mini_profiler/views.rb,
lib/mini_profiler/config.rb,
lib/mini_profiler/actions.rb,
lib/mini_profiler/version.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: Actions, ActiveRecordInstrumentation, ProfilingMethods, TimerStruct, Views Classes: AbstractStore, ClientSettings, Config, Context, FileStore, GCProfiler, MemcacheStore, MemoryStore, NoBrainerProfiler, RedisStore, SnapshotsTransporter

Constant Summary collapse

VERSION =
"3.3.1"
SOURCE_CODE_URI =
"https://github.com/MiniProfiler/rack-mini-profiler"
ASSET_VERSION =
'116e2a6fd81c286e004e2a0afb03baa1'

Constants included from Views

Views::BLANK_PAGE

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ProfilingMethods

counter, counter_method, finish_step, profile_method, profile_singleton_method, record_sql, report_reader_duration, start_step, step, uncounter_method, unprofile_method, unprofile_singleton_method

Methods included from Views

#blank_page_html, #flamegraph, #generate_html, #get_profile_script, #help, #make_link, #public_base_path, #resources_root, #share_template, #url_for_snapshot, #url_for_snapshots_group

Methods included from Actions

#serve_file, #serve_flamegraph, #serve_profile_gc, #serve_profile_memory, #serve_results, #serve_snapshot

Constructor Details

#initialize(app, config = nil) ⇒ MiniProfiler

options: :auto_inject - should script be automatically injected on every html page (not xhr)



122
123
124
125
126
127
128
129
130
131
# File 'lib/mini_profiler.rb', line 122

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.storage_options)
  end
  @storage = @config.storage_instance
end

Class Attribute Details

.subscribe_sql_active_recordObject

Returns the value of attribute subscribe_sql_active_record.



25
26
27
# File 'lib/mini_profiler.rb', line 25

def subscribe_sql_active_record
  @subscribe_sql_active_record
end

Class Method Details

.add_snapshot_custom_field(key, value) ⇒ Object



55
56
57
58
59
# File 'lib/mini_profiler.rb', line 55

def add_snapshot_custom_field(key, value)
  thread_var_key = :mini_profiler_snapshot_custom_fields
  Thread.current[thread_var_key] ||= {}
  Thread.current[thread_var_key][key] = value
end

.advanced_tools_messageObject



91
92
93
94
95
# File 'lib/mini_profiler.rb', line 91

def advanced_tools_message
  <<~TEXT
    This feature is disabled by default, to enable set the enable_advanced_debugging_tools option to true in Mini Profiler config.
  TEXT
end

.authorize_requestObject



79
80
81
# File 'lib/mini_profiler.rb', line 79

def authorize_request
  Thread.current[:mp_authorized] = true
end

.binds_to_params(binds) ⇒ Object



97
98
99
100
101
102
103
104
105
106
# File 'lib/mini_profiler.rb', line 97

def binds_to_params(binds)
  return if binds.nil? || config.max_sql_param_length == 0
  # map ActiveRecord::Relation::QueryAttribute to [name, value]
  params = binds.map { |c| c.kind_of?(Array) ? [c.first, c.last] : [c.name, c.value] }
  if (skip = config.skip_sql_param_names)
    params.map { |(n, v)| n =~ skip ? [n, nil] : [n, v] }
  else
    params
  end
end

.configObject

So we can change the configuration if we want



40
41
42
# File 'lib/mini_profiler.rb', line 40

def config
  @config ||= Config.default
end

.create_current(env = {}, options = {}) ⇒ Object



70
71
72
73
74
75
76
77
# File 'lib/mini_profiler.rb', line 70

def create_current(env = {}, options = {})
  # 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

.currentObject



44
45
46
# File 'lib/mini_profiler.rb', line 44

def current
  Thread.current[:mini_profiler_private]
end

.current=(c) ⇒ Object



48
49
50
51
52
53
# File 'lib/mini_profiler.rb', line 48

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_snapshot_custom_fields] = nil
  Thread.current[:mp_ongoing_snapshot] = nil
  Thread.current[:mini_profiler_private] = c
end

.deauthorize_requestObject



83
84
85
# File 'lib/mini_profiler.rb', line 83

def deauthorize_request
  Thread.current[:mp_authorized] = nil
end

.discard_resultsObject

discard existing results, don’t track this request



66
67
68
# File 'lib/mini_profiler.rb', line 66

def discard_results
  self.current.discard = true if current
end

.generate_idObject



31
32
33
# File 'lib/mini_profiler.rb', line 31

def generate_id
  rand(36**20).to_s(36)
end

.get_snapshot_custom_fieldsObject



61
62
63
# File 'lib/mini_profiler.rb', line 61

def get_snapshot_custom_fields
  Thread.current[:mini_profiler_snapshot_custom_fields]
end

.patch_rails?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/mini_profiler.rb', line 27

def patch_rails?
  !!defined?(Rack::MINI_PROFILER_ENABLE_RAILS_PATCHES)
end

.redact_sql_queries?Boolean

Returns:

  • (Boolean)


113
114
115
116
# File 'lib/mini_profiler.rb', line 113

def redact_sql_queries?
  Thread.current[:mp_ongoing_snapshot] == true &&
  Rack::MiniProfiler.config.snapshots_redact_sql_queries
end

.request_authorized?Boolean

Returns:

  • (Boolean)


87
88
89
# File 'lib/mini_profiler.rb', line 87

def request_authorized?
  Thread.current[:mp_authorized]
end

.reset_configObject



35
36
37
# File 'lib/mini_profiler.rb', line 35

def reset_config
  @config = Config.default
end

.snapshots_transporter?Boolean

Returns:

  • (Boolean)


108
109
110
111
# File 'lib/mini_profiler.rb', line 108

def snapshots_transporter?
  !!config.snapshots_transport_destination_url &&
  !!config.snapshots_transport_auth_key
end

Instance Method Details

#action_parameters(env) ⇒ Object



419
420
421
# File 'lib/mini_profiler.rb', line 419

def action_parameters(env)
  query_params = Rack::Utils.parse_nested_query(env['QUERY_STRING'])
end

#advanced_debugging_enabled?Boolean

Returns:

  • (Boolean)


149
150
151
# File 'lib/mini_profiler.rb', line 149

def advanced_debugging_enabled?
  config.enable_advanced_debugging_tools
end

#analyze_memoryObject



525
526
527
528
529
530
531
532
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/mini_profiler.rb', line 525

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

#cache_control_valueObject



618
619
620
# File 'lib/mini_profiler.rb', line 618

def cache_control_value
  86400
end

#call(env) ⇒ Object



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
361
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/mini_profiler.rb', line 157

def call(env)
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  client_settings = ClientSettings.new(env, @storage, start)
  MiniProfiler.deauthorize_request if @config.authorization_mode == :allow_authorized

  status = headers = body = nil
  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 = matches_action?('skip', env) || (
    @config.skip_paths &&
    @config.skip_paths.any? do |p|
      if p.instance_of?(String)
        path.start_with?(p)
      elsif p.instance_of?(Regexp)
        p.match?(path)
      end
    end
  )
  if skip_it
    return client_settings.handle_cookie(@app.call(env))
  end

  skip_it = (@config.pre_authorize_cb && !@config.pre_authorize_cb.call(env))

  if skip_it || (
    @config.authorization_mode == :allow_authorized &&
    !client_settings.has_valid_cookie?
  )
    if take_snapshot?(path)
      return client_settings.handle_cookie(take_snapshot(env, start))
    else
      return client_settings.handle_cookie(@app.call(env))
    end
  end

  # handle all /mini-profiler requests here
  if path.start_with? @config.base_url_path
    file_name = path.sub(@config.base_url_path, '')

    case file_name
    when 'results'
      return serve_results(env)
    when 'snapshots'
      self.current = nil
      return serve_snapshot(env)
    when 'flamegraph'
      return serve_flamegraph(env)
    end

    return client_settings.handle_cookie(serve_file(env, file_name: file_name))
  end

  has_disable_cookie = client_settings.disable_profiling?
  # manual session disable / enable
  if matches_action?('disable', env) || has_disable_cookie
    skip_it = true
  end

  if matches_action?('enable', env)
    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.handle_cookie([status, headers, body])
  end

  # remember that profiling is not disabled (ie enabled)
  client_settings.disable_profiling = false

  # profile gc
  if matches_action?('profile-gc', env)
    current.measure = false if current
    return serve_profile_gc(env, client_settings)
  end

  # profile memory
  if matches_action?('profile-memory', env)
    return serve_profile_memory(env, client_settings)
  end

  # any other requests past this point are going to the app to be profiled

  MiniProfiler.create_current(env, @config)

  if matches_action?('normal-backtrace', env)
    client_settings.backtrace_level = ClientSettings::BACKTRACE_DEFAULT
  elsif matches_action?('no-backtrace', env)
    current.skip_backtrace = true
    client_settings.backtrace_level = ClientSettings::BACKTRACE_NONE
  elsif matches_action?('full-backtrace', env) || 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 = matches_action?('trace-exceptions', env) && 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 matches_action?('flamegraph', env) || matches_action?('async-flamegraph', env) || env['HTTP_REFERER'] =~ /pp=async-flamegraph/
      if defined?(StackProf) && StackProf.respond_to?(:run)
        # do not sully our profile with mini profiler timings
        current.measure = false
        match_data      = action_parameters(env)['flamegraph_sample_rate']

        if match_data && !match_data[1].to_f.zero?
          sample_rate = match_data[1].to_f
        else
          sample_rate = config.flamegraph_sample_rate
        end

        mode_match_data = action_parameters(env)['flamegraph_mode']

        if mode_match_data && [:cpu, :wall, :object, :custom].include?(mode_match_data[1].to_sym)
          mode = mode_match_data[1].to_sym
        else
          mode = config.flamegraph_mode
        end

        ignore_gc_match_data = action_parameters(env)['flamegraph_ignore_gc']

        if ignore_gc_match_data
          ignore_gc = ignore_gc_match_data == 'true'
        else
          ignore_gc = config.flamegraph_ignore_gc
        end

        flamegraph = StackProf.run(
          mode: mode,
          raw: true,
          aggregate: false,
          interval: (sample_rate * 1000).to_i,
          ignore_gc: ignore_gc
        ) do
          status, headers, body = @app.call(env)
        end
      else
        message = "Please install the stackprof gem and require it: add gem 'stackprof' to your Gemfile"
        status, headers, body = @app.call(env)
        body.close if body.respond_to? :close

        return client_settings.handle_cookie(
          text_result(message, status: status, headers: headers)
        )
      end
    elsif path == '/rack-mini-profiler/requests'
      status, headers, body = [200, { 'Content-Type' => 'text/html' }, [blank_page_html]]
    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.authorization_mode == :allow_authorized && !MiniProfiler.request_authorized?)
    skip_it = true
  end

  return client_settings.handle_cookie([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 = action_parameters(env)
    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.handle_cookie(dump_exceptions exceptions)
  end

  if matches_action?("env", env)
    return tool_disabled_message(client_settings) if !advanced_debugging_enabled?
    body.close if body.respond_to? :close
    return client_settings.handle_cookie(dump_env env)
  end

  if matches_action?("analyze-memory", env)
    return tool_disabled_message(client_settings) if !advanced_debugging_enabled?
    body.close if body.respond_to? :close
    return client_settings.handle_cookie(analyze_memory)
  end

  if matches_action?("help", env)
    body.close if body.respond_to? :close
    return client_settings.handle_cookie(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 && matches_action?("flamegraph", env)
    body.close if body.respond_to? :close
    return client_settings.handle_cookie(self.flamegraph(flamegraph, path, env))
  elsif flamegraph # async-flamegraph
    page_struct[:has_flamegraph] = true
    page_struct[: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.handle_cookie(result) if result
    end
  rescue Exception => e
    if @config.storage_failure != nil
      @config.storage_failure.call(e)
    end
  end

  client_settings.handle_cookie([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



614
615
616
# File 'lib/mini_profiler.rb', line 614

def cancel_auto_inject(env)
  current.inject_js = false
end

#configObject



145
146
147
# File 'lib/mini_profiler.rb', line 145

def config
  @config
end

#currentObject



137
138
139
# File 'lib/mini_profiler.rb', line 137

def current
  MiniProfiler.current
end

#current=(c) ⇒ Object



141
142
143
# File 'lib/mini_profiler.rb', line 141

def current=(c)
  MiniProfiler.current = c
end

#dump_env(env) ⇒ Object



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/mini_profiler.rb', line 497

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



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/mini_profiler.rb', line 479

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.message.lines.first.chomp}\"\n  #{e.backtrace.join("\n  ")}\n\n"
    end
  end
  text_result(body)
end

#flamegraph_path(env) ⇒ Object



609
610
611
# File 'lib/mini_profiler.rb', line 609

def flamegraph_path(env)
  @config.base_url_path + 'flamegraph?id=' + current.page_struct[:id]
end

#ids(env) ⇒ Object



596
597
598
599
600
601
602
603
# File 'lib/mini_profiler.rb', line 596

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



605
606
607
# File 'lib/mini_profiler.rb', line 605

def ids_comma_separated(env)
  ids(env).join(",")
end

#inject(fragment, script) ⇒ Object



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/mini_profiler.rb', line 458

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

    safe_script = script
    if script.respond_to?(:html_safe)
      safe_script = script.html_safe
    end

    fragment.insert(index, safe_script)
  else
    fragment
  end
end

#inject_profiler(env, status, headers, body) ⇒ Object



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/mini_profiler.rb', line 423

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_comma_separated(env)
    headers['X-MiniProfiler-Flamegraph-Path'] = flamegraph_path(env) if current.page_struct[:has_flamegraph]
  end

  if current.inject_js && content_type =~ /text\/html/
    response = Rack::Response.new([], status, headers)
    script   = self.get_profile_script(env, headers)

    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

#matches_action?(action, env) ⇒ Boolean

Returns:

  • (Boolean)


414
415
416
417
# File 'lib/mini_profiler.rb', line 414

def matches_action?(action, env)
  env['QUERY_STRING'] =~ /#{@config.profile_parameter}=#{action}/ ||
    env['HTTP_X_RACK_MINI_PROFILER'] == action
end

#text_result(body, status: 200, headers: nil) ⇒ Object



591
592
593
594
# File 'lib/mini_profiler.rb', line 591

def text_result(body, status: 200, headers: nil)
  headers = (headers || {}).merge('Content-Type' => 'text/plain; charset=utf-8')
  [status, headers, [body]]
end

#tool_disabled_message(client_settings) ⇒ Object



153
154
155
# File 'lib/mini_profiler.rb', line 153

def tool_disabled_message(client_settings)
  client_settings.handle_cookie(text_result(Rack::MiniProfiler.advanced_tools_message))
end

#trim_strings(strings, max_size) ⇒ Object



519
520
521
522
523
# File 'lib/mini_profiler.rb', line 519

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



133
134
135
# File 'lib/mini_profiler.rb', line 133

def user(env)
  @config.user_provider.call(env)
end