Class: StackProf::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/stackprof/middleware.rb

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware


5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/stackprof/middleware.rb', line 5

def initialize(app, options = {})
  @app       = app
  @options   = options
  @num_reqs  = options[:save_every] || nil

  Middleware.mode     = options[:mode] || :cpu
  Middleware.interval = options[:interval] || 1000
  Middleware.raw      = options[:raw] || false
  Middleware.enabled  = options[:enabled]
  options[:path]      = 'tmp/' if options[:path].to_s.empty?
  Middleware.path     = options[:path]
  at_exit{ Middleware.save } if options[:save_at_exit]
end

Class Attribute Details

.enabledObject

Returns the value of attribute enabled


34
35
36
# File 'lib/stackprof/middleware.rb', line 34

def enabled
  @enabled
end

.intervalObject

Returns the value of attribute interval


34
35
36
# File 'lib/stackprof/middleware.rb', line 34

def interval
  @interval
end

.modeObject

Returns the value of attribute mode


34
35
36
# File 'lib/stackprof/middleware.rb', line 34

def mode
  @mode
end

.pathObject

Returns the value of attribute path


34
35
36
# File 'lib/stackprof/middleware.rb', line 34

def path
  @path
end

.rawObject

Returns the value of attribute raw


34
35
36
# File 'lib/stackprof/middleware.rb', line 34

def raw
  @raw
end

Class Method Details

.enabled?(env) ⇒ Boolean


36
37
38
39
40
41
42
# File 'lib/stackprof/middleware.rb', line 36

def enabled?(env)
  if enabled.respond_to?(:call)
    enabled.call(env)
  else
    enabled
  end
end

.saveObject


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/stackprof/middleware.rb', line 44

def save
  if results = StackProf.results
    path = Middleware.path
    is_directory = path != path.chomp('/')

    if is_directory
      filename = "stackprof-#{results[:mode]}-#{Process.pid}-#{Time.now.to_i}.dump"
    else
      filename = File.basename(path)
      path = File.dirname(path)
    end

    FileUtils.mkdir_p(path)
    File.open(File.join(path, filename), 'wb') do |f|
      f.write Marshal.dump(results)
    end
    filename
  end
end

Instance Method Details

#call(env) ⇒ Object


19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/stackprof/middleware.rb', line 19

def call(env)
  enabled = Middleware.enabled?(env)
  StackProf.start(mode: Middleware.mode, interval: Middleware.interval, raw: Middleware.raw) if enabled
  @app.call(env)
ensure
  if enabled
    StackProf.stop
    if @num_reqs && (@num_reqs-=1) == 0
      @num_reqs = @options[:save_every]
      Middleware.save
    end
  end
end