Skip to content

Instantly share code, notes, and snippets.

@damncabbage
Created December 14, 2012 05:00
Show Gist options
  • Save damncabbage/4282814 to your computer and use it in GitHub Desktop.
Save damncabbage/4282814 to your computer and use it in GitHub Desktop.
Sinatra with rake db:create task taking configuration via a Heroku-style DATABASE_URL environment variable.
source :rubygems
gem 'rake'
gem 'sinatra'
gem 'activerecord'
gem 'sinatra-activerecord'
# Adapters
gem 'mysql2'
gem 'pg'
require 'sinatra/activerecord/rake'
namespace :db do
desc "Create database based on a DATABASE_URL"
task :create do
config = uri_to_config ENV['DATABASE_URL']
begin
case config['adapter']
when /sqlite/
if File.exist?(config['database'])
$stderr.puts "#{config['database']} already exists"
else
# Create the SQLite database; just connecting is enough to create it.
ActiveRecord::Base.establish_connection config
ActiveRecord::Base.connection
end
when /mysql/
create_options = nil
ActiveRecord::Base.establish_connection config.merge('database' => nil)
ActiveRecord::Base.connection.create_database config['database'], create_options
ActiveRecord::Base.establish_connection config
when /postgresql/
encoding = config['encoding'] || ENV['CHARSET'] || 'utf8'
ActiveRecord::Base.establish_connection config.merge('database' => 'postgres', 'schema_search_path' => 'public')
ActiveRecord::Base.connection.create_database config['database'], config.merge('encoding' => encoding)
ActiveRecord::Base.establish_connection config
end
rescue Exception => e
$stderr.puts e, *(e.backtrace)
$stderr.puts "Couldn't create database for #{config.inspect}."
end
end
def uri_to_config(uri)
begin
uri = URI.parse(uri)
rescue URI::InvalidURIError
raise "Invalid DATABASE_URL"
end
{
'adapter' => (uri.scheme == 'postgres' ? 'postgresql' : uri.scheme),
'database' => (uri.scheme.match(/sqlite/) ? uri.path : uri.path[1..-1]),
'username' => uri.user,
'password' => uri.password,
'host' => uri.host,
'port' => uri.port,
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment