forked from mongodb/mongoid
-
Notifications
You must be signed in to change notification settings - Fork 22
/
factory.rb
108 lines (101 loc) · 3.06 KB
/
factory.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
105
106
107
108
# encoding: utf-8
require "mongoid/sessions/mongo_uri"
module Mongoid
module Sessions
module Factory
extend self
# Create a new session given the named configuration. If no name is
# provided, return a new session with the default configuration. If a
# name is provided for which no configuration exists, an error will be
# raised.
#
# @example Create the session.
# Factory.create(:secondary)
#
# @param [ String, Symbol ] name The named session configuration.
#
# @raise [ Errors::NoSessionConfig ] If no config could be found.
#
# @return [ Moped::Session ] The new session.
#
# @since 3.0.0
def create(name = nil)
return default unless name
config = Mongoid.sessions[name]
raise Errors::NoSessionConfig.new(name) unless config
create_session(config)
end
# Get the default session.
#
# @example Get the default session.
# Factory.default
#
# @raise [ Errors::NoSessionConfig ] If no default configuration is
# found.
#
# @return [ Moped::Session ] The default session.
#
# @since 3.0.0
def default
create_session(Mongoid.sessions[:default])
end
private
# Create the session for the provided config.
#
# @api private
#
# @example Create the session.
# Factory.create_session(config)
#
# @param [ Hash ] configuration The session config.
#
# @return [ Moped::Session ] The session.
#
# @since 3.0.0
def create_session(configuration)
raise Errors::NoSessionsConfig.new unless configuration
config, options = parse(configuration)
configuration.merge!(config) if configuration.delete(:uri)
session = Moped::Session.new(config[:hosts], options)
session.use(config[:database])
if authenticated?(config)
session.login(config[:username], config[:password])
end
session
end
# Are we authenticated with this session config?
#
# @api private
#
# @example Is this session authenticated?
# Factory.authenticated?(config)
#
# @param [ Hash ] config The session config.
#
# @return [ true, false ] If we are authenticated.
#
# @since 3.0.0
def authenticated?(config)
config.has_key?(:username) && config.has_key?(:password)
end
# Parse the configuration. If a uri is provided we need to extract the
# elements of it, otherwise the options are left alone.
#
# @api private
#
# @example Parse the config.
# Factory.parse(config)
#
# @param [ Hash ] config The configuration.
#
# @return [ Array<Hash> ] The configuration, parsed.
#
# @since 3.0.0
def parse(config)
options = config[:options].try(:dup) || {}
parsed = config.has_key?(:uri) ? MongoUri.new(config[:uri]).to_hash : config
[ parsed, options ]
end
end
end
end