Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not access response.body inside after filter block in Sinatra 1.0

Tags:

ruby

sinatra

I'm struggling with a strange issue. According to http://github.com/sinatra/sinatra (secion Filters) a response object is available in after filter blocks in Sinatra 1.0. However the response.status is correctly accessible, I can not see non-empty response.body from my routes inside after filter.

I have this rackup file:

config.ru

require 'app'
run TestApp

Then Sinatra 1.0.b gem installed using:

gem install --pre sinatra

And this is my tiny app with a single route:

app.rb

require 'rubygems'
require 'sinatra/base'

class TestApp < Sinatra::Base

  set :root, File.dirname(__FILE__)

  get '/test' do
    'Some response'
  end

  after do
    halt 500 if response.empty? # used 500 just for illustation
  end

end

And now, I would like to access the response inside the after filter. When I run this app and access /test URL, I got a 500 response as if the response is empty, but the response clearly is 'Some response'.

Along with my request to /test, a separate request to /favicon.ico is issued by the browser and that returns 404 as there is no route nor a static file. But I would expect the 500 status to be returned as the response should be empty.

In console, I can see that within the after filter, the response to /favicon.ico is something like 'Not found' and response to /test really is empty even though there is response returned by the route.

What do I miss?

like image 993
Petr Vostrel Avatar asked Mar 20 '10 19:03

Petr Vostrel


1 Answers

The response.body is set Sinatra::Base#invoke, which wraps around Sinatra::Base#dispatch!, which in turn calls the filters. However, #invoke sets the response body after dispatch! is done, therefore the body is not yet set. What you want to do is probably better solved with a rack middleware.

like image 74
Konstantin Haase Avatar answered Sep 30 '22 02:09

Konstantin Haase