Created
June 13, 2012 13:20
-
-
Save stiller/2923987 to your computer and use it in GitHub Desktop.
Rate limiting specific Rails routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RateConstraint | |
def matches?(request) | |
last_request = request.session[:request_time] | |
request.session[:request_time] = Time.now | |
!(last_request and (Time.now - last_request < 2.second)) | |
end | |
end | |
Application.routes.draw do | |
constraints RateConstraint.new do | |
# Routes within this constraint will fail if the requests occur within 2 seconds of each other. | |
# This should be faster than rate limiting using the controllers and models. | |
# Rack middleware would probably be faster still, but I prefer the routes approach. | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment