aneta_bielska [:blog]

Datamapper + Sinatra + PG/Sqlite3
#sinatra #pg #sqlite3

Datamapper is a ruby ORM. In previous article I was writing about alternative to Active Record ORMs. And in this post I will go into more setup details of Datamapper. I picked Datamapper because I wanted to give it a try. Thing I like about DM is that you don’t need to add migrations. All you need are models and a bit of configuration.

Add necessary gems:

# Gemfile

gem 'data_mapper'
gem 'dm-core'

group :development do
  gem 'dm-sqlite-adapter'
  gem 'sqlite3'
end

group :production do
  gem 'dm-postgres-adapter'
  gem 'pg'
end

Datamapper configuration:

# app.rb

require 'data_mapper'
require 'dm-core'
# require all models here

DataMapper::setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/db_name.db")
DataMapper.finalize.auto_upgrade!

ENV['DATABASE_URL'] will be useful for production server (here: Heroku) for postgresql configuration.

Add models:

# animal.rb

require 'data_mapper'
require './breed.rb'

class Animal
  include DataMapper::Resource

  property :id, Serial
  property :name, String
  # . . .
  # more properties

  # add relations
  belongs_to :breed

  # add validations
  validates_within :gender, set: [ 'f', 'm']
end

# breed.rb
require 'data_mapper'
require './animal.rb'

class Breed
  include DataMapper::Resource

  property :id, Serial
  property :type, String
  # . . .

  has n, :animals
end

What was really surprising to me were finder methods. Check those examples:

Animal.all(Animal.breed.type => 'cat')
# in SQL => SELECT * FROM animals
#           INNER JOIN breeds ON animals.breed_id = breeds.id
#           WHERE breeds.type = "dog"

Zoo.all(state: 'ready') + Zoo.all(:age.lte => 2)
# in SQL => SELECT * FROM animals WHERE ("state" = "ready" OR "age" <= 2)

For more information check datamapper.org

If you are wondering how to display sql query, here is a way to go:

collection = Entry.all(id: 2..4, text: 'text')
query = collection.query
DataMapper.repository.adapter.send(:select_statement, query)


For more details visit my project on github (this commit in particular) and check live app on heroku.

You may also enjoy:


#servers (1) #hosting (1) #sinatra (2) #assets (1) #sprockets (1) #react-js (1) #data-mapper (1) #ROM (1) #sequel (1) #ORM (1) #pg (1) #sqlite3 (1) #postgresql (1) #ruby (4) #ubuntu (1) #heroku (1) #git (1) #css (3) #cors (1) #same-origin-policy (1) #rake (1) #web-scraping (1) #ruby-on-rails (1) #brug (1) #elixir (1) #benchmark (1)