Skip to content
alexch edited this page Sep 13, 2010 · 15 revisions

Sinatra-REST

Actually it’s a set of templates to introduce RESTful routes in Sinatra. The
only thing for you to do is to provide the views behind the routes.

Installation

Guess what!

sudo gem source —add http://gems.github.com sudo gem install blindgaenger-sinatra-rest

Usage

Of course you need to require the gem in your sinatra application:

require ‘rubygems’ require ‘sinatra’ require ‘sinatra/rest’

It’s very similar to defining routes in Sinatra (get, post, …). But this
time you don’t define the routes by yourself, but use the model’s name for
convention.

For example, if the model’s class is called Person you only need to add this
line:

rest Person

Which will add the following RESTful routes to your application. (Note the
pluralization of Person to the /people/* routes.)

Verb Route Controller View
GET /people index /people/index.haml
GET /people/new new /people/new.haml
POST /people create redirect to show
GET /people/1 show /people/show.haml
GET /people/1/edit edit /people/edit.haml
PUT /people/1 update redirect to show
DELETE /people/1 destroy redirect to index

As you can see, each route is also associated with a named code block in the
controller. The controller does the minimum to make the routes work. Based on
the route it treates the model and redirects or renders the expected view.

So imagine the following steps to show a single person:

  1. request from the client’s browser
    GET http://localhost:4567/people/99
  2. Find and set @person in the controller
    @person = Person.find_by_id(99)
  3. render the view to display @person
    render VIEW_DIR/people/show.haml

It’s up to you to provide the views, because this goes beyond the restful
routing. The variable @person is correctly named and injected into the view.
So maybe you’d like to do something like this:


  <html>
  <body>
    <div>ID: <%= @person.id %></div>
    <div>Name: <%= @person.name %></div>
  </body>
  </html>

That’s it!

Contact

You can contact me via mail at blindgaenger at gmail dot com, or leave me a
message on my Github profile.

Clone this wiki locally