Skip to content
This repository has been archived by the owner on Jul 18, 2022. It is now read-only.

Commit

Permalink
Add middleware & railtie
Browse files Browse the repository at this point in the history
  • Loading branch information
alisaifee committed Mar 26, 2017
1 parent d7f0b77 commit 1119c40
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/robinet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@ def require_libs(*libs)
end
self.root_path = File.expand_path '..', __FILE__
self.lib_path = File.expand_path '../robinet', __FILE__
require_libs 'storage', 'strategy', 'parser', 'limit'
require_libs(
'config', 'errors', 'storage', 'strategy',
'parser', 'limit', 'limiter', 'railtie', 'middleware'
)
end
12 changes: 12 additions & 0 deletions lib/robinet/limiter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module Robinet
class Limiter

def initialize(app)
@app = app
end

def execute(request)
raise Errors::RateLimitExceeded
end
end
end
24 changes: 24 additions & 0 deletions lib/robinet/middleware.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module Robinet
class Middleware
def initialize(app)
@app = app
@limiter = Robinet::Limiter.new(@app)
end

def call(env)
request = Rack::Request.new(env)
begin
check_limits(request)
@app.call(env)
rescue Errors::RateLimitExceeded => e
e.http_response
end
end

private

def check_limits(request)
@limiter.execute(request)
end
end
end
10 changes: 10 additions & 0 deletions lib/robinet/railtie.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module Robinet
class Railtie < Rails::Railtie
initializer 'robinet.add_middleware' do |application|
if Robinet.config.enabled
Robinet.logger.info('Enabling Robinet Rate Limiter')
application.middleware.use Robinet::Middleware
end
end
end if defined?(Rails)
end

0 comments on commit 1119c40

Please sign in to comment.