A Very Basic Ruby Rack App
Sometimes I write very small web applications. I like to have the power and flexibility of ruby and my libraries, but I don’t want to drag around a huge web stack like Rails or even Merb. For this there is the great interface of Rack.
From the rack project:
Rack provides an minimal interface between webservers supporting Ruby and Ruby frameworks.
So here are the basics of using rack in a [semi]useful project:
First, we install the gem:
gem install rack
Then we implement a very basic app. Save this as “app.ru”.
use Rack::ShowExceptions
use Rack::CommonLogger
require ‘rack/request’
require ‘rack/response’
module Rack
class App
def call(env)
req = Request.new(env)
Response.new.finish do |res|
res.write(“”)
res.write req.fullpath
res.write(“”)
end
end
end
end
run Rack::App.new
Next we need to run a server. The rackup command should be installed with the rack gem.
rackup app.ru -p 3000
This fires up one of the rack handlers. It defaults to either using Mongrel or Webrick.
Now in your web browser go to http://localhost:3000/this/is/the/path.
Magic, right? Now if you also need this application of yours to be screaming fast and not need to lean on [crappy] ruby threading, we need to add EventMachine, which is one of the greatest additions to Ruby network programming ever. The easiest way to do this is to use Thin.
From the Thin site:
Thin is a Ruby web server that glues together 3 of the best Ruby libraries in web history:
- the Mongrel parser, the root of Mongrel speed and security
- Event Machine, a network I/O library with extremely high scalability, performance and stability
- Rack, a minimal interface between webservers and Ruby frameworks
Which makes it, with all humility, the most secure, stable, fast and extensible Ruby web server bundled in an easy to use gem for your own pleasure.
The next steps are easy for all that goodness.
gem install thin
thin start -R app.ru
Stick that in your pipe and smoke it!
