Skip to content

Commit 5d4057d

Browse files
committed
Add ability to use multiple instances of middleware
1 parent b6ce502 commit 5d4057d

File tree

3 files changed

+45
-22
lines changed

3 files changed

+45
-22
lines changed

lib/rack/attack.rb

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,16 @@ def reset!
9696

9797
attr_reader :configuration
9898

99-
def initialize(app)
99+
def initialize(app, &block)
100100
@app = app
101-
@configuration = self.class.configuration
101+
@configuration =
102+
if block_given?
103+
configuration = Configuration.new
104+
configuration.instance_exec(&block)
105+
configuration
106+
else
107+
self.class.configuration
108+
end
102109
end
103110

104111
def call(env)

spec/acceptance/middleware_spec.rb

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "../spec_helper"
4+
5+
describe "Middleware" do
6+
it "is used in Rails by default" do
7+
skip unless defined?(Rails)
8+
9+
app = Class.new(Rails::Application) do
10+
config.eager_load = false
11+
config.logger = Logger.new(nil) # avoid creating the log/ directory automatically
12+
config.cache_store = :null_store # avoid creating tmp/ directory for cache
13+
end
14+
15+
app.initialize!
16+
assert app.middleware.include?(Rack::Attack)
17+
end
18+
19+
def app
20+
Rack::Builder.new do
21+
use Rack::Attack do
22+
blocklist_ip("1.2.3.4")
23+
end
24+
25+
run lambda { |_env| [200, {}, ['Hello World']] }
26+
end.to_app
27+
end
28+
29+
it "can be configured via a block" do
30+
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
31+
assert_equal 403, last_response.status
32+
33+
get "/", {}, "REMOTE_ADDR" => "4.3.2.1"
34+
assert_equal 200, last_response.status
35+
end
36+
end

spec/acceptance/rails_middleware_spec.rb

Lines changed: 0 additions & 20 deletions
This file was deleted.

0 commit comments

Comments
 (0)