Class: Rack::Delay

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/delay.rb

Constant Summary collapse

HEADER =
'X-Rack-Delay'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Delay.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rack/delay.rb', line 7

def initialize(app, options={})
  @app     = app
  
  if options.has_key?(:unless)
    options[:if] = options.delete(:unless)
    options[:negate] = true
  end

  @options = {
      :min    => 50,     # msec
      :max    => 5000,   # msec
      :delay  => nil,
      :if     => nil,
      :negate => false
    }.merge(options)
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



5
6
7
# File 'lib/rack/delay.rb', line 5

def app
  @app
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/rack/delay.rb', line 5

def options
  @options
end

Instance Method Details

#_call_block(block, request) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/rack/delay.rb', line 34

def _call_block(block, request)
  if block.arity == 0
    block.call()
  else
    block.call(request)
  end
end

#call(env) ⇒ Object



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
# File 'lib/rack/delay.rb', line 42

def call(env)
  request = Rack::Request.new(env)
  should_delay = true
  
  
  should_delay = !!_call_block(options[:if], request) if options[:if]
  should_delay = !should_delay if options[:negate]

  header_delay = 'none'
  
  if should_delay

    min_delay = options[:min]
    max_delay = options[:max]

    if options[:delay]
      ret = _call_block(options[:delay], request)
      unless ret.nil?
        ret = [ret] unless ret.kind_of?(Array)
        min_delay = ret.first
        max_delay = ret.last
      end
    end

    delay = peek_delay(min_delay, max_delay)
    header_delay = delay
    sleep(delay)
  end
  
  status , headers , response = app.call(env)
  headers[ HEADER ] = header_delay.to_s
  [status , headers , response]
end

#peek_delay(min, max) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/rack/delay.rb', line 24

def peek_delay(min, max)
  if min > max
    tmp = max
    max = min
    min = tmp
  end
  return min / 1000.0 if min == max
  (min + rand(max - min)) / 1000.0
end