Skip to content

Instantly share code, notes, and snippets.

@dmitry-ilyashevich
Forked from oivoodoo/post-checkout.rb
Created June 28, 2012 12:45
Show Gist options
  • Save dmitry-ilyashevich/3011155 to your computer and use it in GitHub Desktop.
Save dmitry-ilyashevich/3011155 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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment