# Attempt to serve static files from public directory. Throws :halt when
# a matching file is found, returns nil otherwise.
def static!
  return if (public_dir = configs.public).nil?
  public_dir = File.expand_path(public_dir)

  path = File.expand_path(public_dir + unescape(request.path_info))
  return if path[0, public_dir.length] != public_dir
  return unless File.file?(path)

  env['sinatra.static_file'] = path
  send_file path, :disposition => nil
end


# Dispatch a request with error handling.
def dispatch!
  static! if configs.static? && (request.get? || request.head?)
  filter! :before
  route!
rescue NotFound => boom
  handle_not_found!(boom)
rescue ::Exception => boom
  handle_exception!(boom)
ensure
  filter! :after unless env['sinatra.static_file']
end