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 May 4, 2024
1 parent b6ce502 commit 5d4057d
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 22 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
36 changes: 36 additions & 0 deletions spec/acceptance/middleware_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# frozen_string_literal: true

require_relative "../spec_helper"

describe "Middleware" do
it "is used in Rails by default" do
skip unless defined?(Rails)

app = Class.new(Rails::Application) do
config.eager_load = false
config.logger = Logger.new(nil) # avoid creating the log/ directory automatically
config.cache_store = :null_store # avoid creating tmp/ directory for cache
end

app.initialize!
assert app.middleware.include?(Rack::Attack)
end

def app
Rack::Builder.new do
use Rack::Attack do
blocklist_ip("1.2.3.4")
end

run lambda { |_env| [200, {}, ['Hello World']] }
end.to_app
end

it "can be configured via a block" do
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
20 changes: 0 additions & 20 deletions spec/acceptance/rails_middleware_spec.rb

This file was deleted.

0 comments on commit 5d4057d

Please sign in to comment.