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: http://nvie.com/posts/a-successful-git-branching-model/. 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'
...
end
# config/database.yml
<% repo = Rugged::Repository.new(Rails.root.to_s) %>
<% branch = repo.head.name.sub(/^refs\/heads\//, '') %>
default: &default
adapter: mysql2
pool: 5
host: localhost
username: root
password:
development:
<<: *default
database: <%= branch == 'develop' ? 'myapp_development' : "myapp_development_#{branch.underscore}" %>
test:
<<: *default
database: myapp_test
Hope that helps.