Skip to content
Rack middleware port of Rails's respond_to feature
Find file
Latest commit d74c390 @mynyml Update README
Failed to load latest commit information.
examples Add catch-all format example app
lib/rack Support catch-all format
test Support catch-all format
.gitignore Added temporary unix files and vim swap files to the git ignore list.
LICENSE Initial commit
Manifest Add catch-all format example app Update README
Rakefile Simplify gem handling and Rakefile
docs.watchr Add docs.watchr script
rack-respond_to.gemspec v0.9.8
specs.watchr Added specs.watchr script


Rack convenience middleware that allows triggering different actions based on requested media type. Standalone version of the equivalent Rails functionality.


  • Based on familiar API (Rails)
  • Cascades down priority list of accepted media types
  • Handles wildcard media types
  • Simple to use
  • Simple code (~50 LOCs)
  • Flexible (standalone use)
  • Decently documented (examples/ dir, source docs/rdocs)
  • Compatible with other media type handling middleware (uses Rack::AcceptMediaTypes)


gem install rack-respond_to


require 'rack'
require 'rack/respond_to'

class App
  include Rack::RespondTo #mixes in #respond_to

  def call(env)
    # Pass in the env, and RespondTo will retrieve the requested media types
    Rack::RespondTo.env = env

    # Alternatively, to use standalone you can also assign the media types
    # directly (this will take precedence over the env)
    #Rack::RespondTo.media_types = ['text/html']

    body = respond_to do |format|
      format.html { '<em>html</em>' }
      format.xml  { '<body>xml</body>' }

    [200, {'Content-Type' => Rack::RespondTo.selected_media_type}, [body]]


See examples/ for an executable example.


Use together with Rack::AbstractFormat to respond to routes based on url extensions. For example, if you want to trigger the format.xml block (Rack::AbstractFormat moves the extension's media type into HTTP_ACCEPT and makes it the highest ranked).

gem install rack-abstract-format

See examples/ for a complete example.


  • thanks to daicoden for format.any idea and initial patch


Something went wrong with that request. Please try again.