Last active
July 28, 2016 10:03
-
-
Save ka8725/7877933 to your computer and use it in GitHub Desktop.
database.yml generator. Global Rake implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'yaml' | |
desc 'Generates database.yml, optional arguments: [adapter, user, password]' | |
task :dbconfig => 'database.yml' | |
file 'database.yml', [:adapter, :username, :password] do |t, args| | |
Dir.chdir('config') | |
args.with_defaults(:project_path => Dir.pwd) | |
DBConfigGenerator.new(t, args).generate | |
end | |
class DBConfigGenerator | |
ENVIRONMENTS = %w(production development test) | |
DEFAULTS = { | |
'adapter' => 'postgresql', | |
'encoding' => 'unicode', | |
'username' => Etc.getlogin, | |
'pool' => 5, | |
'password' => nil | |
} | |
def initialize(task, options = {}) | |
@database_pattern = "#{options[:project_path].pathmap('%-1d')}_%s" | |
@template = {} | |
@output_file = task.name | |
@defaults = DEFAULTS.tap do |defaults| | |
defaults.each_key do |k| | |
defaults[k] = options[k] if options[k] | |
end | |
end | |
end | |
def generate | |
ENVIRONMENTS.each do |env| | |
@template[env] = @defaults.merge('database' => @database_pattern % env) | |
end | |
File.write(@output_file, @template.to_yaml) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put this code into
~/.rake/dbconfig.rake
file and you will be able to generatedatabase.yml
in any your rails project with this command:rake -g dbconfig
. It won't regenerate the config again if it's already exists. So if you want to regenerate it you should delete it before.Default options for each environment are:
They may be changed though command line:
rake -g "dbconfig[adapter, usr, pwd]"