Database Setup for the Sinatra App

The database setup for our Sinatra app consists of the following:

  • A database config file — database.yml — where we define the database settings for the development, production, and test databases.
  • Database adapter and ORM gems included in the Gemfile. We are using ActiveRecord for our app. Datamapper is another option you could use.
  • Registering the ORM extension and the database config file in app.rb.

Here’s the database config file:

yaml

# config/database.yml default: &default adapter: sqlite3 pool: 5 timeout: 5000 development: <<: *default database: db/development.sqlite3 test: <<: *default database: db/test.sqlite3 production: adapter: postgresql encoding: unicode pool: 5 host: <%= ENV['DATABASE_HOST'] || 'db' %> database: <%= ENV['DATABASE_NAME'] || 'sinatra' %> username: <%= ENV['DATABASE_USER'] || 'sinatra' %> password: <%= ENV['DATABASE_PASSWORD'] || 'sinatra' %>

And the ORM and database adaptor gems in the Gemfile:

ruby

# Gemfile source "https://rubygems.org" # Ruby version ruby "3.0.4" gem 'sinatra' gem 'activerecord' gem 'sinatra-activerecord' # ORM gem gem 'sinatra-contrib' gem 'thin' gem 'rake' gem 'faraday' group :development do gem 'sqlite3' # Development database adaptor gem gem 'tux' # gives you access to an interactive console similar to 'rails console' gem 'dotenv' end group :production do gem 'pg' # Production database adaptor gem end

And here’s how you register the ORM and database config in app.rb.

ruby

# app.rb module LivingCostCalc class App < Sinatra::Base # global settings configure do ... register Sinatra::ActiveRecordExtension end # database settings set :database_file, 'config/database.yml' ... end end

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *