forked from afeld/mongo_ruby_workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo_wrapper.rb
69 lines (54 loc) · 1.43 KB
/
mongo_wrapper.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
require 'json'
require 'mongo'
class MongoWrapper
include Mongo
def connection
@connection ||= MongoClient.new('localhost', 27017)
end
def db
@db ||= self.connection['mongo_ruby_demo']
end
# remove all non-built-in collections
def clear
self.db.collections.each do |coll|
coll.remove unless coll.name.start_with?('system.')
end
end
# returns a cached copy
def checkin_seed_data
unless @checkin_seed_data
# read in the dummy data
json_str = File.read('./data/checkins.json')
json = JSON.parse(json_str)
@checkin_seed_data = json['response']['recent']
end
@checkin_seed_data
end
def add_checkin(checkin)
# don't modify the hash
checkin = checkin.dup
# remove the embedded data
user = checkin.delete 'user'
venue = checkin.delete 'venue'
user_id = self.db['users'].insert user
venue_id = self.db['venues'].insert venue
# reference those newly-created documents
checkin['user_id'] = user_id
checkin['venue_id'] = venue_id
self.db['checkins'].insert checkin
end
def seed
checkins = self.checkin_seed_data
checkins.each do |checkin|
self.add_checkin checkin
end
# just a sanity check
raise "not all checkins loaded" unless checkins.size == self.db['checkins'].count
end
end
if __FILE__ == $0
# file being run directly - reset the DB
wrapper = MongoWrapper.new
wrapper.clear
wrapper.seed
end