For some reason, in a Sinatra “after” filter I can’t seem to access the current status code
require 'rubygems'
require 'sinatra'
after do
puts "After hook with code: #{response.status}"
end
get '/hi' do
halt(401, "wtf?")
end
When running curl 127.0.0.1:4567/hi, it results in:
After hook for code: 200
It’s basically a function of how the methods are implemented in Sinatra. The methods we need to pay attention to are
call!,invokeanddispatch!, all methods in Sinatra::Base (as of v1.3.2).call!is the top level method, and in there, it calls the following line of code:Now,
invokelooks like this:It actually sets the response code on the basis of the thing you
throwwith:halt. Anddispatch!looks like:See that
ensureblock? That gets run as the:haltsymbol that has beenthrownsails up the stack trace. Crucially, this is before the status setting code is run.