Skip to content
Jrgns edited this page Sep 13, 2018 · 1 revision

This page speaks to some of the Opinions in Ditty.

Object relational mapping libraries are a great tool to help abstract the database layer in any application. Ruby on Rails uses ActiveRecord, but Sinatra doesn't come with an ORM out of the box. The ORM used by Ditty is called Sequel by Jeremy Evans.

Background

Sequel is branded as a database toolbox, which means you get tools such as migrations, schema translations and various plugins along with it. The heaviest use for it in Ditty, though, is it's ORM capabilities.

Connecting to the DB

Ditty will automatically connect to the DB defined in the DATABASE_URL environment variable. It will also setup logging for the connection on the DEBUG level if the DB_DEBUG environment variable is set to 1. The level can be changed using the SEQUEL_LOGGING_LEVEL, but our recommendation to keep it to DEBUG since the logs are quite verbose.

The connection setup can be seen in lib/ditty/db.rb

Models

Models are generally stored in the models folder, and represent data objects in your application. Sequel models can be really lightweight, and can be defined in a couple of lines:

require 'sequel'
require 'ditty/models/base'

module Ditty
  class User < ::Sequel::Model
    include ::Ditty::Base
  end
end

The code above defines a model called Ditty::User. It's persisted to the users table (which is inferred from the model name). It's common to encode your business logic within these models. Take a look at Ditty's User model for a more complete example.

Associations

An important feature of databases is to link data together. This customer record has multiple transaction records linked to it. These associations are implemented using foreign keys on a database level. In Sequel they are defined using associations.

Migrations

Sequel also provides migration capabilities that allows you to create, remove and modify tables and fields within your database. Migration files should be stored in the folder defined by the migrations folder of a component, or in the migrations folder in the root of the project.

Migrations are invoked using the ditty:migrate rake task:

bundle exec rake ditty:migrate

Plugins used

The following Sequel plugins are automatically enabled in Ditty

  • validation_helpers - Add easy to use and read validation methods to models
  • update_or_create - Make it easy to update an existing record, or create one if it doesn't exist yet.
  • timestamps - Automatically set and update the created_at and updated_at fields of a record.
  • pagination - Adds Dataset#paginate for easier pagination of datasets

Clone this wiki locally