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 =
'1.1.0'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of RateLimit.



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

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

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



13
14
15
# File 'lib/rack/attack/rate-limit.rb', line 13

def app
  @app
end

#optionsObject (readonly)

Returns the value of attribute options.



13
14
15
# File 'lib/rack/attack/rate-limit.rb', line 13

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



52
53
54
55
56
57
# File 'lib/rack/attack/rate-limit.rb', line 52

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

#call(env) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/rack/attack/rate-limit.rb', line 20

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



39
40
41
# File 'lib/rack/attack/rate-limit.rb', line 39

def default_options
  { throttle: 'throttle' }
end

#rack_attack_keyObject

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

Returns string



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

def rack_attack_key
  RACK_ATTACK_KEY
end

#throttleObject



43
44
45
# File 'lib/rack/attack/rate-limit.rb', line 43

def throttle
  Array(options[:throttle]) || []
end