From f23dd26acf2a18d9e5b01853c84597aab1c9255a Mon Sep 17 00:00:00 2001 From: fatkodima Date: Thu, 17 Oct 2019 14:30:45 +0300 Subject: [PATCH] Add ability to use multiple instances of middleware --- lib/rack/attack.rb | 11 +++++++++-- spec/acceptance/rails_middleware_spec.rb | 12 ++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/rack/attack.rb b/lib/rack/attack.rb index c9094b21..de273f4c 100644 --- a/lib/rack/attack.rb +++ b/lib/rack/attack.rb @@ -96,9 +96,16 @@ def reset! attr_reader :configuration - def initialize(app) + def initialize(app, &block) @app = app - @configuration = self.class.configuration + @configuration = + if block_given? + configuration = Configuration.new + configuration.instance_exec(&block) + configuration + else + self.class.configuration + end end def call(env) diff --git a/spec/acceptance/rails_middleware_spec.rb b/spec/acceptance/rails_middleware_spec.rb index 31dc6209..9d02819a 100644 --- a/spec/acceptance/rails_middleware_spec.rb +++ b/spec/acceptance/rails_middleware_spec.rb @@ -16,5 +16,17 @@ @app.initialize! assert @app.middleware.include?(Rack::Attack) end + + it "can be configured via a block" do + @app.middleware.delete(Rack::Attack) + @app.middleware.use(Rack::Attack) do + blocklist_ip("1.2.3.4") + end + get "/", {}, "REMOTE_ADDR" => "1.2.3.4" + assert_equal 403, last_response.status + + get "/", {}, "REMOTE_ADDR" => "4.3.2.1" + assert_equal 200, last_response.status + end end end