Sunday, August 19, 2012

Sinatra Rolodex App with DataMapper

I am on the lookout for how I can use Sinatra with a database. I found this script from > Sinatra. The author claims it's a rolodex app written in Sinatra, using DataMapper.

Here is the link to the article... Creating Database-driven Apps with Sinatra -

I am posting this here so I can play with it, to see how I can make it work for me.

#!/usr/bin/env ruby
 require 'rubygems'
 require 'sinatra'
 require 'haml'
 require 'dm-core'
 DataMapper.setup( :default, "sqlite3://#{Dir.pwd}/rolodex.db" )
 # Define the model
 class Contact
   include DataMapper::Resource
   property :id, Serial
   property :firstname, String
   property :lastname, String
   property :email, String
 # Show list of contacts
 get '/contacts/' do
   haml :list, :locals => { :cs => Contact.all }
 # Show form to create new contact
 get '/contacts/new' do
   haml :form, :locals => {
     :c =>,
     :action => '/contacts/create'
 # Create new contact
 post '/contacts/create' do
   c =
   c.attributes = params
 # Show form to edit contact
 get '/contacts/:id/edit' do|id|
   c = Contact.get(id)
   haml :form, :locals => {
     :c => c,
     :action => "/contacts/#{}/update"
 # Edit a contact
 post '/contacts/:id/update' do|id|
   c = Contact.get(id)
   c.update_attributes params
   redirect "/contacts/#{id}"
 # Delete a contact
 post '/contacts/:id/destroy' do|id|
   c = Contact.get(id)
   redirect "/contacts/"
 # View a contact
 # TODO: Put at bottom?
 get '/contacts/:id' do|id|
   c = Contact.get(id)
   haml :show, :locals => { :c => c }
 @@ layout
     %title Rolodex
     = yield
     %a(href="/contacts/") Contact List
 %h1 Create a new contact
 %form(action="#{action}" method="POST")
   %label(for="firstname") First Name
   %input(type="text" name="firstname" value="#{c.firstname}")
   %label(for="lastname") Last Name
   %input(type="text" name="lastname" value="#{c.lastname}")
   %label(for="email") Email
   %input(type="text" name="email" value="#{}")
 - unless == 0
   %form(action="/contacts/#{}/destroy" method="POST")
     %input(type="submit" value="Destroy")
     %td First Name
     %td= c.firstname
     %td Last Name
     %td= c.lastname
     %td Email
 %a(href="/contacts/#{}/edit") Edit Contact
 %h1 Contacts
 %a(href="/contacts/new") New Contact
   - cs.each do|c|
       %td= c.firstname
       %td= c.lastname
         %a(href="/contacts/#{}") Show
         %a(href="/contacts/#{}/edit") Edit

No comments:

Post a Comment