/
use_db.rb
67 lines (58 loc) · 1.84 KB
/
use_db.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# UseDb
module UseDbPlugin
# options can have one or the other of the following options:
# :prefix - Specify the prefix to append to the RAILS_ENV when finding the adapter secification in database.yml
# :suffix - Just like :prefix, only contactentated
# OR
# :adapter
# :host
# :username
# :password
# ... etc ... same as the options in establish_connection
#
# Set the following to true in your test environment
# to enable extended debugging printing during testing ...
# UseDbPlugin.debug_print = true
#
@@use_dbs = [ActiveRecord::Base]
@@debug_print = false
def use_db(options)
options_dup = options.dup
conn_spec = get_use_db_conn_spec(options)
puts "Establishing connecting on behalf of #{self.to_s} to #{conn_spec.inspect}" if UseDbPlugin.debug_print
establish_connection(conn_spec)
extend ClassMixin
@@use_dbs << self unless @@use_dbs.include?(self) || self.to_s.starts_with?("TestModel")
end
def self.all_use_dbs
return @@use_dbs
end
def self.debug_print
return @@debug_print
end
def self.debug_print=(newval)
@@debug_print = newval
end
module ClassMixin
def uses_db?
true
end
end
def get_use_db_conn_spec(options)
options.symbolize_keys
suffix = options.delete(:suffix)
prefix = options.delete(:prefix)
rails_env = options.delete(:rails_env) || RAILS_ENV
if (options[:adapter])
return options
else
str = "#{prefix}#{rails_env}#{suffix}"
connections = YAML.load(ERB.new(IO.read("#{RAILS_ROOT}/config/database.yml"), nil, nil, '_use_db_erbout').result)
raise "Cannot find database specification. Configuration '#{str}' expected in config/database.yml" if (connections[str].nil?)
return connections[str]
end
end
end
class UseDbPluginClass
extend UseDbPlugin
end