ShiftEleven

Forget About Little Old CGI

Maybe someone may have told you to use ruby and CGI together, but I think that person has a screw loose. I mean, come on. Everyone knows that what you really need to use is Rack

Why Rack

Well for one, it's light weight. So if you want to deploy your ruby script using CGI, you can do that with Rack.

But let's say, you want to your script to Mongrel, or WEBRick, or FCGI; you can do that too, and with very few changes to your script. That's because Rack abstracts all the boilerplate code you would need to work with those servers and bundles it up into a nice interface for you to use.

Oh, and the code to use Rack is very easy. Here's an example of a Rack app for you:

Examples

 1%w(rubygems rack haml).each { |dep| require dep }
 2
 3class IndexPage
 4  def call(env)
 5    haml_engine = Haml::Engine.new(File.read('../templates/index.haml'))
 6    [
 7      200,
 8      { "Content-Type" => "text/html" },
 9      haml_engine.render(Object.new, {})
10    ]
11  end
12end
13
14Rack::Handler::CGI.run(IndexPage.new)

The secret behind Rack is that it will run any ruby object that has a call method and pass in the environment variables to it. In that environment variable, you will find things like HTTP_HOST, or QUERY_STRING, and the like.

If you wanted to have this script now work with WEBRick, no problem.

1# Same code as above, with just a little tweak to the last line
2
3Rack::Handler::WEBRick.run(IndexPage.new, :Port => 3000)

Tada! So now you can run a test server without worrying about setting up Apache or Lighttpd.

More Goodness

To make your life easier, Rack also comes with a set of middleware for you to use. Say you have an error in your application. Perhaps you would like to see that error formatted nicely in your browser. You can enable Rack::ShowExceptions. Perhaps you would like the code you have to be reloaded from the server whenever it changes, like when you're developing your application, then you can use Rack::Reloader.

To use those options, you can write your Rack handler like

1app = Rack::Builder.new do
2  use Rack::CommonLogger  # apache-like logger
3  use Rack::ShowExceptions
4  use Rack::Reloader
5  use Rack::ShowStatus  # create default pages for common HTTP error codes
6  use Rack::Lint  #ensures all applications behave validly
7  run Index.new
8end
9Rack::Handler::WEBRick.run(app, :Port => 3000)

There's plenty of magic going on with Rack; A magic that does not sacrifice speed and/or flexibility. I would highly recommend giving Rack a look into the next time you want to write a simple web page.

Comments

comments powered by Disqus