# File lib/sinatra/respond_to.rb, line 59
    def self.registered(app)

      app.helpers RespondTo::Helpers

      app.before do

        # Skip development error image and static content
        next if self.class.development? && request.path_info =~ %r{/__sinatra__/.*?.png}
        next if options.static? && options.public? && (request.get? || request.head?) && static_file?(request.path_info)

        # Remove extension from URI
        # Extension will be available as a 'extension' method (extension=='txt')
       
        extension request.path_info.match(/\.([^\.\/]+)$/).to_a.first

        # If ?format= is present, ignore all Accept negotiations because
        # we are not dealing with browser
        if request.params.has_key? 'format'
          format params['format'].to_sym
        end
        
        # Let's make a little exception here to handle
        # /api/instance_states[.gv/.png] calls
        if extension.eql?('gv')
          format :gv
        elsif extension.eql?('png')
          format :png
        end

        # Get Rack::Accept::Response object and find best possible
        # mime type to output.
        # This negotiation works fine with latest rest-client gem:
        #
        # RestClient.get 'http://localhost:3001/api', {:accept => :json } =>
        # 'application/json'
        # RestClient.get 'http://localhost:3001/api', {:accept => :xml } =>
        # 'application/xml'
        #
        # Also browsers like Firefox (3.6.x) and Chromium reporting
        # 'application/xml+xhtml' which is recognized as :html reponse
        # In browser you can force output using ?format=[format] parameter.

        rack_accept = env['rack-accept.request']

        if rack_accept.media_type.to_s.strip.eql?('Accept:')
          format :xml
        elsif is_chrome?
          format :html
        else
          format lookup_format_from_mime(rack_accept.best_media_type(accept_to_array))
        end

      end

      app.class_eval do

        # Simple helper to detect Chrome based browsers
        # which have screwed up they Accept headers.
        # Set HTML as default output format here
        def is_chrome?
          true if env['HTTP_USER_AGENT'] =~ /Chrome/
        end

        # This code was copied from respond_to plugin
        # http://github.com/cehoffman/sinatra-respond_to
        # MIT License
        alias :render_without_format :render
        def render(*args, &block)
          assumed_layout = args[1] == :layout
          args[1] = "#{args[1]}.#{format}".to_sym if args[1].is_a?(::Symbol)
          render_without_format *args, &block
        rescue Errno::ENOENT => e
          raise MissingTemplate, "#{args[1]}.#{args[0]}" unless assumed_layout
          raise e
        end
        private :render
      end

      # This code was copied from respond_to plugin
      # http://github.com/cehoffman/sinatra-respond_to
      app.configure :development do |dev|
        dev.error MissingTemplate do
          content_type :html, :charset => 'utf-8'
          response.status = request.env['sinatra.error'].code

          engine = request.env['sinatra.error'].message.split('.').last
          engine = 'haml' unless ['haml', 'builder', 'erb'].include? engine

          path = File.basename(request.path_info)
          path = "root" if path.nil? || path.empty?

          format = engine == 'builder' ? 'xml' : 'html'

          layout = case engine
                   when 'haml' then "!!!\n%html\n  %body= yield"
                   when 'erb' then "<html>\n  <body>\n    <%= yield %>\n  </body>\n</html>"
                   end

          layout = "<small>app.#{format}.#{engine}</small>\n<pre>#{escape_html(layout)}</pre>"

          ("<!DOCTYPE html>\n<html>\n<head>\n<style type=\"text/css\">\nbody { text-align:center;font-family:helvetica,arial;font-size:22px;\ncolor:#888;margin:20px}\n#c {margin:0 auto;width:500px;text-align:left;}\nsmall {float:right;clear:both;}\npre {clear:both;text-align:left;font-size:70%;width:500px;margin:0 auto;}\n</style>\n</head>\n<body>\n<h2>Sinatra can't find \#{request.env['sinatra.error'].message}</h2>\n<img src='/__sinatra__/500.png'>\n<pre>\#{request.env['sinatra.error'].backtrace.join(\"\\n\")}</pre>\n<div id=\"c\">\n<small>application.rb</small>\n<pre>\#{request.request_method.downcase} '\#{request.path_info}' do\\n  respond_to do |wants|\\n    wants.\#{format} { \#{engine} :\#{path} }\\n  end\\nend</pre>\n</div>\n</body>\n</html>\n").gsub(/^ {10}/, '')
        end

      end
    end