Using Rack

August 20, 2008

I heve been experimenting with Rack for a while and thought I would write a short post about it here.

In essence, Rack is an API that sits between your web framework and the webserver itself. A basic Rack application consists of a call method that takes a hash of environmen variabes such as whre the request comes from and returns a hash of variables containing a status code, content-type and a response string.

A minimal Rack application is listed below:

  %w(rubygems rack).each {|dep| require dep}

  app = lambda{|env| [200, {}, 'Another Test!']}

  Rack::Handler::Mongrel.run(app, :P ort=> 3000)

Make sure the Rack gem in installed onto your local system first. Fire up the console and run the script.

You will see a flashing command prompt as the script is waiting to receive a HTTP request. Type ‘http://localhost:3000/’ into your browser an you should see the string ‘Another Test’ being returned to the browser.

I utilised the technique above to create a middleware class in my ongoing Merb application to handle file uploads away from the framework itself but stilll being able to access certain components of the framework (i.e. ActiveRecord objects) if needs to. An example of how to accomplish this can be found on Ezra’s blog(the creator of Merb).

A snippet of the middleware code will be made available soon after refactoring.

Leave a Reply

You must be logged in to post a comment.