提交 a2cb90c0 编写于 作者: C Carlhuda

Refactor script/dbconsole into an object

上级 d8c5ea76
......@@ -2,10 +2,16 @@
require 'yaml'
require 'optparse'
include_password = false
options = {}
module Rails
class DBConsole
def self.start
new.start
end
OptionParser.new do |opt|
def start
include_password = false
options = {}
OptionParser.new do |opt|
opt.banner = "Usage: dbconsole [options] [environment]"
opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
include_password = true
......@@ -22,15 +28,15 @@
opt.parse!(ARGV)
abort opt.to_s unless (0..1).include?(ARGV.size)
end
end
env = ARGV.first || ENV['RAILS_ENV'] || 'development'
unless config = YAML::load(ERB.new(IO.read(Rails.root + "/config/database.yml")).result)[env]
env = ARGV.first || ENV['RAILS_ENV'] || 'development'
unless config = YAML::load(ERB.new(IO.read("#{Rails.root}/config/database.yml")).result)[env]
abort "No database is configured for the environment '#{env}'"
end
end
def find_cmd(*commands)
def find_cmd(*commands)
dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
commands += commands.map{|cmd| "#{cmd}.exe"} if RUBY_PLATFORM =~ /win32/
......@@ -42,10 +48,10 @@ def find_cmd(*commands)
end
end
found ? full_path_command : abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
end
end
case config["adapter"]
when "mysql"
case config["adapter"]
when "mysql"
args = {
'host' => '--host',
'port' => '--port',
......@@ -64,17 +70,17 @@ def find_cmd(*commands)
exec(find_cmd('mysql', 'mysql5'), *args)
when "postgresql"
when "postgresql"
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password
exec(find_cmd('psql'), config["database"])
when "sqlite"
when "sqlite"
exec(find_cmd('sqlite'), config["database"])
when "sqlite3"
when "sqlite3"
args = []
args << "-#{options['mode']}" if options['mode']
......@@ -82,6 +88,9 @@ def find_cmd(*commands)
args << config['database']
exec(find_cmd('sqlite3'), *args)
else
else
abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
end
end
end
end
\ No newline at end of file
require File.expand_path('../../config/application', __FILE__)
require 'rails/commands/dbconsole'
Rails::DBConsole.start
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册