Ruby on Rails: Switching MySQL Database Based On Current Git Branch

At Dexcode, we uses Git heavily and follow the Git flow process described here: Often times, we work on a separate branch which modifies the existing databases or sometimes the master and develop branch is so far apart that we wish that the database switch automatically when we switch branch.

To solve this problem, we use rugged gem which gives us Ruby API to access Git. All we need to do is add rugged to the Gemfile and modify database.yml.

# Gemfile

group :development do  
  gem 'rugged'
# config/database.yml

<% repo = %>  
<% branch =^refs\/heads\//, '') %>

default: &default  
  adapter: mysql2
  pool: 5
  host: localhost
  username: root

  <<: *default
  database: <%= branch == 'develop' ? 'myapp_development' : "myapp_development_#{branch.underscore}" %>

  <<: *default
  database: myapp_test

Hope that helps.