Permalink
Browse files

Fix redirect/halt in before filters [#85]

  • Loading branch information...
rtomayko committed Jan 18, 2009
1 parent 968194d commit 8a4d1a0b5c82ed3833e00111d39bd4a4879d6330
Showing with 29 additions and 4 deletions.
  1. +4 −4 lib/sinatra/base.rb
  2. +25 −0 test/filter_test.rb
View
@@ -328,7 +328,7 @@ def pass
private
def dispatch!
- self.class.filters.each {|block| instance_eval(&block)}
+ self.class.filters.each { |block| invoke(block) }
if routes = self.class.routes[@request.request_method]
path = @request.path_info
original_params = nested_params(@request.params)
@@ -382,6 +382,8 @@ def indifferent_hash
def invoke(block)
res = catch(:halt) { instance_eval(&block) }
+ return if res.nil?
+
case
when res.respond_to?(:to_str)
@response.body = [res]
@@ -405,8 +407,6 @@ def invoke(block)
@response.body = res
when (100...599) === res
@response.status = res
- when res.nil?
- @response.body = []
end
res
end
@@ -522,7 +522,7 @@ def media_type(type)
end
def before(&block)
- @filters << block
+ @filters << lambda { instance_eval(&block) ; nil }
end
def condition(&block)
View
@@ -32,4 +32,29 @@
assert ok?
assert_equal 'bar', body
end
+
+ it "allows redirects in filters" do
+ mock_app {
+ before { redirect '/bar' }
+ get('/foo') { 'ORLY?!' }
+ }
+
+ get '/foo'
+ assert redirect?
+ assert_equal '/bar', response['Location']
+ end
+
+ it "does not modify the response with its return value" do
+ mock_app {
+ before { 'Hello World!' }
+ get '/foo' do
+ assert_equal [], response.body
+ 'cool'
+ end
+ }
+
+ get '/foo'
+ assert ok?
+ assert_equal 'cool', body
+ end
end

0 comments on commit 8a4d1a0

Please sign in to comment.