-
Notifications
You must be signed in to change notification settings - Fork 7
/
mongo.rb
78 lines (61 loc) · 1.75 KB
/
mongo.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
module AppConfig
module Storage
require 'mongo'
# Mongo storage method.
class Mongo < Storage::Base
DEFAULTS = {
host: 'localhost',
port: 27017,
database: 'app_config',
collection: 'app_config',
username: nil,
password: nil,
}
def initialize(options)
# Allows passing `true` as an option.
if options.is_a?(Hash)
@options = DEFAULTS.merge(options)
else
@options = DEFAULTS
end
setup_connection!
fetch_data!
end
# Reload the data from storage. Returns `true`/`false`.
def reload!
fetch_data!
end
# Saves the data back to Mongo. Returns `true`/`false`.
def save!
if @_id
retval = collection.update({ '_id' => @_id}, @data.to_hash)
else
retval = collection.save(@data.to_hash)
end
!!retval
end
private
def authenticate_connection!
database.authenticate(@options[:username], @options[:password])
end
def connected?
@connection && @connection.connected?
end
def collection
@collection ||= database.collection(@options[:collection])
end
def database
@database ||= @connection.db(@options[:database])
end
def fetch_data!
raise 'Not connected to MongoDB' unless connected?
@data = Storage::ConfigData.new(collection.find_one)
@_id = @data._id
end
def setup_connection!
@connection = ::Mongo::Connection.new(@options[:host], @options[:port].to_i)
authenticate_connection! if @options[:username] && @options[:password]
end
end # Mongo
end # Storage
end # AppConfig