Skip to content

Commit

Permalink
Add ability to use multiple instances of middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Nov 15, 2023
1 parent ffc2102 commit f23dd26
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/rack/attack.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions spec/acceptance/rails_middleware_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit f23dd26

Please sign in to comment.