/
connection.rb
104 lines (86 loc) · 2.52 KB
/
connection.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# encoding: UTF-8
require 'uri'
module MongoMapper
module Connection
@@connection = nil
@@database = nil
@@database_name = nil
@@config = nil
# @api public
def connection
@@connection ||= Mongo::MongoClient.new
end
# @api public
def connection=(new_connection)
@@connection = new_connection
end
# @api public
def logger
connection.logger
end
# @api public
def database=(name)
@@database = nil
@@database_name = name
end
# @api public
def database
return nil if @@database_name.blank?
@@database ||= MongoMapper.connection.db(@@database_name)
end
def config=(hash)
@@config = hash
end
def config
raise 'Set config before connecting. MongoMapper.config = {...}' unless defined?(@@config)
@@config
end
# @api private
def config_for_environment(environment)
env = config[environment.to_s] || {}
return env if env['uri'].blank?
uri = URI.parse(env['uri'])
raise InvalidScheme.new('must be mongodb') unless uri.scheme == 'mongodb'
{
'host' => uri.host,
'port' => uri.port,
'database' => uri.path.gsub(/^\//, ''),
'username' => uri.user,
'password' => uri.password,
}
end
def connect(environment, options={})
raise 'Set config before connecting. MongoMapper.config = {...}' if config.blank?
env = config_for_environment(environment)
if env['options'].is_a?(Hash)
options = env['options'].symbolize_keys.merge(options)
end
if env.key?('ssl')
options[:ssl] = env['ssl']
end
MongoMapper.connection = if env['hosts']
if env['hosts'].first.is_a?(String)
Mongo::MongoReplicaSetClient.new( env['hosts'], options )
else
Mongo::MongoReplicaSetClient.new( *env['hosts'].push(options) )
end
else
Mongo::MongoClient.new(env['host'], env['port'], options)
end
MongoMapper.database = env['database']
MongoMapper.database.authenticate(env['username'], env['password']) if env['username'] && env['password']
end
def setup(config, environment, options={})
handle_passenger_forking
self.config = config
connect(environment, options)
end
def handle_passenger_forking
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
connection.connect if forked
end
end
end
end
end