This repository has been archived by the owner on Sep 7, 2021. It is now read-only.
/
mingo.rb
266 lines (220 loc) · 6.59 KB
/
mingo.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
require 'active_support/core_ext/hash/conversions'
require 'mongo'
require 'active_model'
require 'hashie/dash'
BSON::ObjectId.class_eval do
def self.[](id)
self === id ? id : from_string(id)
end
def id
self
end
end
class Mingo < Hashie::Dash
include ActiveModel::Conversion
extend ActiveModel::Translation
autoload :Cursor, 'mingo/cursor'
autoload :ManyProxy, 'mingo/many_proxy'
autoload :Persistence, 'mingo/persistence'
autoload :Callbacks, 'mingo/callbacks'
autoload :Changes, 'mingo/changes'
class << self
attr_writer :db, :collection
def db
@db || superclass.db
end
def connect(dbname_or_uri)
self.collection = nil
self.db = if dbname_or_uri.index('mongodb://') == 0
connection = Mongo::Connection.from_uri(dbname_or_uri)
connection.db(connection.auths.last['db_name'])
else
Mongo::Connection.new.db(dbname_or_uri)
end
end
def collection_name
self.name
end
def collection
@collection ||= db.collection(collection_name).tap { |col|
col.extend Cursor::CollectionPlugin
}
end
def first(id_or_selector = nil, options = {})
unless id_or_selector.nil? or Hash === id_or_selector
id_or_selector = BSON::ObjectId[id_or_selector]
end
collection.find_one(id_or_selector, {:convert => self}.update(options))
end
def find(selector = {}, options = {}, &block)
collection.find(selector, {:convert => self}.update(options), &block)
end
def find_by_ids(object_ids, query = {}, options = {})
find({:_id => {'$in' => object_ids}}.update(query), options)
end
def find_ordered_ids(object_ids, query = {}, options = {})
indexed = find_by_ids(object_ids, query, options).inject({}) do |hash, object|
hash[object.id] = object
hash
end
object_ids.map { |id| indexed[id] }
end
def paginate_ids(object_ids, paginate_options, options = {})
object_ids.paginate(paginate_options).tap do |collection|
collection.replace find_ordered_ids(collection, {}, options)
end
end
def many(property, *args, &block)
proxy_class = block_given?? Class.new(ManyProxy, &block) : ManyProxy
ivar = "@#{property}"
define_method(property) {
(instance_variable_defined?(ivar) && instance_variable_get(ivar)) ||
instance_variable_set(ivar, proxy_class.new(self, property, *args))
}
end
end
include Module.new {
def initialize(obj = nil)
if obj and obj['_id'].is_a? BSON::ObjectId
# a doc loaded straight from the db
merge!(obj)
else
super
end
end
}
include Persistence
include Callbacks
include Changes
def id
self['_id']
end
# overwrite these to avoid checking for declared properties
# (which is default behavior in Dash)
def [](property)
_regular_reader(property.to_s)
end
def []=(property, value)
_regular_writer(property.to_s, value)
end
# keys are already strings
def stringify_keys() self end
alias :stringify_keys! :stringify_keys
def ==(other)
other.is_a?(self.class) and other.id == self.id
end
end
if $0 == __FILE__
require 'rspec'
Mingo.connect('mingo')
class User < Mingo
property :name
property :age
end
describe User do
before :all do
User.collection.remove
end
it "obtains an ID by saving" do
user = build :name => 'Mislav'
user.should_not be_persisted
user.id.should be_nil
user.save
raw_doc(user.id)['name'].should == 'Mislav'
user.should be_persisted
user.id.should be_a(BSON::ObjectId)
end
it "tracks changes attribute" do
user = build
user.should_not be_changed
user.name = 'Mislav'
user.should be_changed
user.changes.keys.should include(:name)
user.name = 'Mislav2'
user.changes[:name].should == [nil, 'Mislav2']
user.save
user.should_not be_changed
end
it "forgets changed attribute when reset to original value" do
user = create :name => 'Mislav'
user.name = 'Mislav2'
user.should be_changed
user.name = 'Mislav'
user.should_not be_changed
end
it "has a human model name" do
described_class.model_name.human.should == 'User'
end
it "can reload values from the db" do
user = create :name => 'Mislav'
user.update '$unset' => {:name => 1}, '$set' => {:age => 26}
user.age.should be_nil
user.reload
user.age.should == 26
user.name.should be_nil
end
it "saves only changed values" do
user = create :name => 'Mislav', :age => 26
user.update '$inc' => {:age => 1}
user.name = 'Mislav2'
user.save
user.reload
user.name.should == 'Mislav2'
user.age.should == 27
end
it "unsets values set to nil" do
user = create :name => 'Mislav', :age => 26
user.age = nil
user.save
raw_doc(user.id).tap do |doc|
doc.should_not have_key('age')
doc.should have_key('name')
end
end
context "existing doc" do
before do
@id = described_class.collection.insert :name => 'Mislav', :age => 26
end
it "finds a doc by string ID" do
user = described_class.first(@id.to_s)
user.id.should == @id
user.name.should == 'Mislav'
user.age.should == 26
end
it "is unchanged after loading" do
user = described_class.first(@id)
user.should_not be_changed
user.age = 27
user.should be_changed
user.changes.keys.should == [:age]
end
it "doesn't get changed by an inspect" do
user = described_class.first(@id)
# triggers AS stringify_keys, which dups the Dash and writes to it,
# which mutates the @changes hash from the original Dash
user.inspect
user.should_not be_changed
end
end
it "returns nil for non-existing doc" do
doc = described_class.first('nonexist' => 1)
doc.should be_nil
end
it "compares with another record" do
one = create :name => "One"
two = create :name => "Two"
one.should_not == two
one_dup = described_class.first(one.id)
one_dup.should == one
end
def build(*args)
described_class.new(*args)
end
def create(*args)
described_class.create(*args)
end
def raw_doc(selector)
described_class.first(selector, :convert => nil)
end
end
end