Rewriting content types with Rack 2008-03-22

UPDATE: I have just added another Rack entry: Rack Middleware: Adding cache headers

Rack is a common API between webservers and frameworks for Ruby. It allows all kinds of nice stuff, like chaining filters that each do one small and self-contained part of the processing and are easy to reuse.

Here's a trivial one I wrote to automatically set Content-Type based on the extension of a file:

# Rewrite content types based on file extensions
class RewriteContentType
  def initialize app, opts
    @app = app
    @map = opts

  def call env
    res =
    ext = env["PATH_INFO"].split(".")[-1]
    res[1]["Content-Type"] = @map[ext] if @map.has_key?(ext)

All it does is split off anything after the last "." and add a matching Content-Type to the headers if it exists in the map that's passed in. In my Rack config file, I do this:

use RewriteContentType, {"js" => "text/javascript"}

blog comments powered by Disqus