Skip to content

Instantly share code, notes, and snippets.

@oivoodoo
Created June 28, 2012 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oivoodoo/3011085 to your computer and use it in GitHub Desktop.
Save oivoodoo/3011085 to your computer and use it in GitHub Desktop.
post-checkout for changing database name in rails projects. place this file into .git/hooks folder.
#!/usr/bin/ruby
require 'yaml'
class Database
attr_reader :config_file, :settings
def initialize
@config_file = File.expand_path(File.join(File.dirname(__FILE__), "../../config/database.yml"))
load_config
end
def change_branch_database!
settings.each do |key, value|
value["database"] = prepare_database_name(value['database'])
end
save_settings
end
private
def prepare_database_name(name)
name.gsub!(/#{delimeter}.+/,'')
return "#{name}#{delimeter}#{branch_name}" unless branch_master?
name
end
def save_settings
File.open(config_file, "w") do |file|
file.write(settings.to_yaml)
end
end
def branch_master?
branch_name == "master"
end
def branch_name
@branch_name ||= `git branch --contains #{ARGV[1]}`.gsub('* ', '').strip
@branch_name
end
def delimeter
"---"
end
def load_config
@settings = YAML.load(File.open(config_file, "r"))
end
end
database = Database.new
database.change_branch_database!
@oivoodoo
Copy link
Author

Example:
master(config/database.yml):

test: 
  adapter: mysql
  encoding: utf8
  database: your_database_test
  username: root
  password: 
  host: 
development: 
  adapter: mysql
  encoding: utf8
  database: your_database
  username: root
  password: 
  host:
git checkout new-branch

You will see new database:

test: 
  adapter: mysql
  encoding: utf8
  database: your_database---new-branch
  username: root
  password: 
  host: 
development: 
  adapter: mysql
  encoding: utf8
  database: your_database---new-branch
  username: root
  password: 
  host:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment