sinatra via passengerrack

Sun, Jul 19, 2009

Raw Rack on Passenger is great for data transfers to a rich client but what if you’re dishing out actual content for a thin client to display? such as an iPhone webapp? (more on that later). Ruby on Rails is a bit too heavyweight for my liking plus I don’t have a database backend it can mess with. So I had a look at Sinatra. It’s a DSL that’s provided by a web micro-framework that lets you easily build REST style “cloud interfaces” (my term). Just what I need for serving iPhone enabled content with iUI. The other good thing about Sinatra is it’s Rack based, which means it can be served from Apache via Passenger. So here’s how to get started with Sinatra on Apache.

First, install Passenger with Apache. Then install Sinatra:

gem install sinatra
Create a new Sinatra app structure in your DocumentRoot:
cd DocumentRoot
mkdir sinatra-hello-world
mkdir sinatra-hello-world/public
ln -s sinatra-hello-world/public shw
cd sinatra-hello-world
create a config.ru file with this in it:
require ‘rubygems’
require ‘sinatra’
require ‘app’

GUBBINS START

class NginxPassengerFix def initialize(app) @app = app end

def call(env) # Very dodgy hax to correct the PATH_INFO env[“PATH_INFO”] = env[“REQUEST_URI”].sub(/\?[^\?]*$/, “”) r = @app.call(env) end end use NginxPassengerFix

GUBBINS STOP

run Sinatra::Application

as of this writing, Sinatra doesn’t work with Passenger 2.2.4 on unix. You’ll get an error like this when it runs:
“GET  ” 404 18 0.0008
The NginxPassengerFix gubbins comes from this helpful solution to the problem.

Create a new file in sinatra-hello-world, app.rb and bung this in it:

get ‘/shw’ do
  “Hello from sinatra!”
end

get ‘/shw/funny_url’ do “Hello from sinatra’s funny URL!” end

Finally, don’t forget to add the new rack application to Apache’s conf in DocumentRoot for the host:
DocumentRoot “/Users/alistair/web/htdocs”
RackBaseURI /shw
Restart Apache and point your browser to:
http://localhost/shw
and then try the free URL you got from Sinatra without having to configure paths in Apache:
http://localhost/shw/funny_url

comments powered by Disqus