Skip to content

Instantly share code, notes, and snippets.

@JesseHerrick
Created June 5, 2015 19:29
Show Gist options
  • Save JesseHerrick/4a3dc6e92603e2ab5990 to your computer and use it in GitHub Desktop.
Save JesseHerrick/4a3dc6e92603e2ab5990 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'optparse'
require 'fileutils'
DB_CONFIG=<<EOF
default: &default
hostname: localhost
adapter: postgresql
development:
database: DB_NAME_dev
<<: *default
test:
database: DB_NAME_test
<<: *default
EOF
def fail(message)
abort "\e[0;31;49m#{message}\e[0m"
end
def cleanup
FileUtils.rm(get_filename)
end
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: database_yml [options] <project>"
opts.on('-f', '--force', 'Force creation of database.yml') do |f|
options[:force] = true
end
end.parse!
def project_name
if ARGV.empty?
get_projectname.downcase
else
ARGV.last.downcase
end
end
def current_dir
Dir.pwd.split('/').last
end
def current_dir?(dir)
current_dir == dir
end
def get_projectname
if in_config?
Dir.pwd.split('/')[-2]
else
current_dir
end
end
def in_config?
current_dir? 'config'
end
# if we're in the config dir already, just let it happen
def get_filename
if in_config?
File.join(Dir.pwd, 'database.yml')
elsif Dir.exist? 'config'
File.join(Dir.pwd, 'config/database.yml')
else
fail "No config directory exists.\nAre you sure you're in a Rails project?"
end
end
def config_with_name(project)
DB_CONFIG.gsub('DB_NAME', project)
end
def create_database_yml
File.open(get_filename, 'w+') do |file|
file.write config_with_name(project_name)
end
end
def create(options)
if File.exist? get_filename
if options[:force]
create_database_yml
else
fail "database.yml aleady exists\nTry with -f to force."
end
else
create_database_yml
end
end
def interface(options)
project_name # first check if args given
puts "Creating database configuration...\nAt: \e[0;34;49m#{get_filename}\e[0m"
create(options)
puts "\e[0;32;49mDone!\e[0m"
end
# and finally... call the method!
interface(options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment