Skip to content

Instantly share code, notes, and snippets.

@ka8725
Last active July 28, 2016 10:03
Show Gist options
  • Save ka8725/7877933 to your computer and use it in GitHub Desktop.
Save ka8725/7877933 to your computer and use it in GitHub Desktop.
database.yml generator. Global Rake implementation
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
@ka8725
Copy link
Author

ka8725 commented Dec 9, 2013

Put this code into ~/.rake/dbconfig.rake file and you will be able to generate database.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:

adapter: postgresql
encoding: unicode
username: <current OS username>
pool: 5
password:
database: <project name>_<environment>

They may be changed though command line: rake -g "dbconfig[adapter, usr, pwd]"

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