Vidar Hokstad V2.0

Home Blog

2008-03-19 06:45 UTC Rewriting content types with Rack

Posted in: , ,
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
  end

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

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"}


No comments yet - Be the first one!

Post a Comment

Basic HTML allowed.

About me

E-mail: vidar@hokstad.com
Skype: vhokstad
View my LinkedIn profile

I was born April 21st, 1975, in Oslo, Norway. Since 2000 I've been living in London, UK. I'm married.

I'm working for Aardvark Media as Director of Technology. I'm also currently on the board of SpatialQ, a startup in the GIS space, and an advisor to Skoach, a startup doing a time management app for people with ADD.

Recent posts to my blog

Categories

StumbleUpon My link page

(Links I have stumbled and like)