Skip to content

Commit 5eb14e2

Browse files
author
Michael Bleigh
committed
Middlewares that take blocks are now supported by API.use
1 parent e159056 commit 5eb14e2

File tree

3 files changed

+32
-4
lines changed

3 files changed

+32
-4
lines changed

lib/grape/api.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
module Grape
77
# The API class is the primary entry point for
8-
# creating Grape APIs. Users should subclass this
8+
# creating Grape APIs.Users should subclass this
99
# class in order to build an API.
1010
class API
1111
class << self
@@ -309,8 +309,10 @@ def scope(name = nil, &block)
309309
#
310310
# @param middleware_class [Class] The class of the middleware you'd like
311311
# to inject.
312-
def use(middleware_class, *args)
313-
imbue(:middleware, [[middleware_class, *args]])
312+
def use(middleware_class, *args, &block)
313+
arr = [middleware_class, *args]
314+
arr << block if block_given?
315+
imbue(:middleware, [arr])
314316
end
315317

316318
# Retrieve an array of the middleware classes

lib/grape/endpoint.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,14 @@ def build_middleware
225225

226226
b.use Grape::Middleware::Formatter, :default_format => settings[:default_format] || :json
227227

228-
aggregate_setting(:middleware).each{|m| b.use *m }
228+
aggregate_setting(:middleware).each do |m|
229+
block = m.pop if m.last.is_a?(Proc)
230+
if block
231+
b.use *m, &block
232+
else
233+
b.use *m
234+
end
235+
end
229236

230237
b
231238
end

spec/grape/api_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,11 +337,13 @@ class PhonyMiddleware
337337
def initialize(app, *args)
338338
@args = args
339339
@app = app
340+
@block = true if block_given?
340341
end
341342

342343
def call(env)
343344
env['phony.args'] ||= []
344345
env['phony.args'] << @args
346+
env['phony.block'] = true if @block
345347
@app.call(env)
346348
end
347349
end
@@ -395,6 +397,23 @@ def call(env)
395397
get '/'
396398
last_response.body.should eql 'hello'
397399
end
400+
401+
it 'should add a block if one is given' do
402+
block = lambda{ }
403+
subject.use PhonyMiddleware, &block
404+
subject.middleware.should eql [[PhonyMiddleware, block]]
405+
end
406+
407+
it 'should use a block if one is given' do
408+
block = lambda{ }
409+
subject.use PhonyMiddleware, &block
410+
subject.get '/' do
411+
env['phony.block'].inspect
412+
end
413+
414+
get '/'
415+
last_response.body.should == 'true'
416+
end
398417
end
399418
end
400419
describe '.basic' do

0 commit comments

Comments
 (0)