Class: Rack::Attack::RateLimit

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/attack/rate-limit.rb,
lib/rack/attack/rate-limit/version.rb

Constant Summary collapse

RACK_ATTACK_KEY =
'rack.attack.throttle_data'
VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of RateLimit.



9
10
11
12
# File 'lib/rack/attack/rate-limit.rb', line 9

def initialize(app, options = {})
  @app = app
  @options = default_options.merge(options)
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



7
8
9
# File 'lib/rack/attack/rate-limit.rb', line 7

def app
  @app
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/rack/attack/rate-limit.rb', line 7

def options
  @options
end

Instance Method Details

#add_rate_limit_headers!(headers, env) ⇒ Object

Return hash of headers with Rate Limiting data

headers - Hash of headers

Returns hash



46
47
48
49
50
# File 'lib/rack/attack/rate-limit.rb', line 46

def add_rate_limit_headers!(headers, env)
  headers['X-RateLimit-Limit']      = rate_limit_limit(env).to_s
  headers['X-RateLimit-Remaining']  = rate_limit_remaining(env).to_s
  headers
end

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/rack/attack/rate-limit.rb', line 14

def call(env)
  # If env does not have necessary data to extract rate limit data for the provider, then app.call
  return app.call(env) unless rate_limit_available?(env)     
  # Otherwise, add rate limit headers
  status, headers, body = app.call(env)
  add_rate_limit_headers!(headers, env)
  [status, headers, body]  
end

#default_optionsObject

Default options to configure Rack::RateLimit

Returns hash



33
34
35
# File 'lib/rack/attack/rate-limit.rb', line 33

def default_options
  { throttle: 'throttle' }
end

#rack_attack_keyObject

Returns env key used by Rack::Attack to namespace data

Returns string



26
27
28
# File 'lib/rack/attack/rate-limit.rb', line 26

def rack_attack_key
  RACK_ATTACK_KEY
end

#throttleObject



37
38
39
# File 'lib/rack/attack/rate-limit.rb', line 37

def throttle
  options[:throttle] || ''
end