Last Updated: February 25, 2016
·
395
· ready4god2513

A Sane database.yml

Rails, thankfully, is all about convention over configuration. I DO NOT miss the days of messing around with a ton of XML files for DI and the such. That said, one thing that is configured in every rails app is database.yml. And even though the docs are clear on it, it can still be a pain to set up every time. Eventually I will create a gem to just install it for me, but here is what I use-

development:
  adapter: postgresql
  encoding: utf8
  database: <%= "#{Rails.application.class.parent_name}-dev-#{`git rev-parse --abbrev-ref HEAD`.strip}".downcase %>
  username: <%= ENV['DB_USER_POSTGRES_USERNAME'] %>
  password: <%= ENV['DB_USER_POSTGRES_PASSWORD'] %>
  host: localhost
  port: 5432

test:
  adapter: postgresql
  encoding: utf8
  database: <%= "#{Rails.application.class.parent_name}-test-#{`git rev-parse --abbrev-ref HEAD`.strip}".downcase %>
  username: <%= ENV['DB_USER_POSTGRES_USERNAME'] %>
  password: <%= ENV['DB_USER_POSTGRES_PASSWORD'] %>
  host: localhost
  port: 5432

The one requirement here is that you are using git with your project. What this will do will be to create a new database schema (postgres) per git branch you are on, use the environment variable for username and password, and keep all other options as their defaults.

The benefit that I have found with using the git branch name in the database name is largely with doing work on a branch (that adds or removes columns/indexes/tables) and then switching to master for a hotfix. All of a sudden you are working against an invalid database state. Some aren't huge fans of this setup, but it works quite well for me.