What's the best way to talk to a database while using Sinatra? What's the best way to talk to a database while using Sinatra? ruby ruby

What's the best way to talk to a database while using Sinatra?


If you're using Sinatra, I can't recommend DataMapper highly enough. I have a couple Rails apps where I'm stuck with ActiveRecord, and I'm constantly cursing its shortcomings and design flaws. If you're on Sinatra, DataMapper is a very practical choice.

require "rubygems"require "sinatra"require "datamapper"DataMapper.setup(:default, "sqlite3::memory:")class Post  include DataMapper::Resource  property :id,    Integer, :serial => true  property :title, StringendPost.auto_migrate!first_post = Post.newfirst_post.title = "First!"first_post.saveget "/" do  Post.get(1).titleend


If you like ActiveRecord, use that. Or something else. Datamapper, for instance. For AR with SQLite, this works:

require 'rubygems' # may not be needed, depending on platformrequire 'sinatra'require 'active_record'class Article < ActiveRecord::Baseendget '/' do  Article.establish_connection(    :adapter => "sqlite3",    :database => "hw.db"  )  Article.first.titleend


It is up to you how to communicate with a database, you may choose either one of the ORMs or some NoSQL adapter. There are many options available, some of them were made specially for Sinatra:

For example, there is Sinatra ActiveRecord Extension
Originally created by Blake Mizerany, creator of Sinatra
It extends Sinatra with ActiveRecord helper methods and Rake tasks

Another option is Sinatra Sequel Extension.
This small extension adds database configuration, migrations, and Sequel adapters right into Sinatra.

Or sinatra-redis, or sinatra-mongo, and so on. Just search for what you want.

But you may as well freely use any independent library, check out the Sinatra Recipes on databases, where is listed a couple of examples of how to use popular database mappers with Sinatra. Although it is mentioned there that the suggested practice for this is using DataMapper, I suspect that this is a mere preference, because nothing in Sinatra itself suggests this.