Created
April 10, 2009 14:33
-
-
Save graemenelson/93100 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'sequel' | |
| # Database | |
| # | |
| # A helper class to wrap calls to Sequel Database, primarily for getting a database from a YAML config | |
| # file and for migrating. | |
| class Database | |
| @@configuration_file = File.join( File.dirname(__FILE__), "../config/database.yml" ) | |
| raise Exception.new("No '#{@@configuration_file}' file was found. ") if @@configuration_file.nil? | |
| @@migration_path = File.join( File.dirname(__FILE__), "../db/migrations" ) | |
| @@configuration = YAML.load( File.open( @@configuration_file ) ) | |
| @@current_database = nil | |
| def self.for_environment( environment, reload = false ) | |
| @@current_database = nil if reload | |
| current_or_connect_to_database_for_environment( environment ) | |
| end | |
| def self.migrate( environment, target = nil, current = nil ) | |
| Sequel::Migrator.apply( for_environment( environment ), @@migration_path, target, current ) | |
| end | |
| def self.reset( environment ) | |
| db = current_or_connect_to_database_for_environment( environment ) | |
| db.tables.each do |table| | |
| db.drop_table table | |
| end | |
| migrate( environment ) | |
| end | |
| private | |
| def self.current_or_connect_to_database_for_environment( environment ) | |
| @@current_database ||= connect_to_database_for_environment( environment ) | |
| end | |
| def self.connect_to_database_for_environment( environment ) | |
| Sequel.connect( connection_string_for( environment ) ) | |
| end | |
| def self.connection_string_for( environment ) | |
| config = @@configuration[environment.to_s] | |
| unless config.nil? | |
| adapter = config['adapter'] | |
| database = config['database'] | |
| username = config['username'] | |
| password = config['password'] | |
| host = config['host'] | |
| port = config['port'] | |
| database_connection_string = "#{adapter}:" | |
| unless username.blank? | |
| database_connection_string << username | |
| database_connection_string << ":#{password}" unless password.blank? | |
| end | |
| unless host.blank? | |
| database_connection_string << "@#{host}" | |
| database_connection_string << ":#{port}" unless port.blank? | |
| end | |
| database_connection_string << (database.blank? ? "/" : "//#{database}") | |
| else | |
| raise Exception.new("No database found for '#{environment}' environment. Please add to #{@@configuration_file}") | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment