Class: Rack::Delay
- Inherits:
-
Object
- Object
- Rack::Delay
- Defined in:
- lib/rack/delay.rb
Constant Summary collapse
- HEADER =
'X-Rack-Delay'
Instance Attribute Summary collapse
-
#app ⇒ Object
readonly
Returns the value of attribute app.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
- #_call_block(block, request) ⇒ Object
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ Delay
constructor
A new instance of Delay.
- #peek_delay(min, max) ⇒ Object
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, ={}) @app = app if .has_key?(:unless) [:if] = .delete(:unless) [:negate] = true end = { :min => 50, # msec :max => 5000, # msec :delay => nil, :if => nil, :negate => false }.merge() end |
Instance Attribute Details
#app ⇒ Object (readonly)
Returns the value of attribute app.
5 6 7 |
# File 'lib/rack/delay.rb', line 5 def app @app end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
5 6 7 |
# File 'lib/rack/delay.rb', line 5 def 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([:if], request) if [:if] should_delay = !should_delay if [:negate] header_delay = 'none' if should_delay min_delay = [:min] max_delay = [:max] if [:delay] ret = _call_block([: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 |