This repository has been archived by the owner on Aug 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
persistence.rb
92 lines (72 loc) · 2.29 KB
/
persistence.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
module LightMongo
# Connection and database getters/setters hoofed from jnunemaker's MongoMapper
def self.connection
@@connection ||= Mongo::Connection.new
end
def self.connection=(new_connection)
@@connection = new_connection
end
def self.database=(name)
@@database = nil
@@database_name = name
end
def self.database
unless defined?(@@database_name) and !Util.blank?(@@database_name)
raise 'You forgot to set the default database name: LightMongo.database = "foobar"'
end
@@database ||= LightMongo.connection.db(@@database_name)
end
module Document
module Persistence
def self.included(document_class)
document_class.extend ClassMethods
document_class.collection = Mongo::Collection.new(LightMongo.database, document_class.name)
end
def collection
self.class.collection
end
def save
@_id = collection.save(self.to_hash)
end
def update(params)
params.each_pair do |attr_name, attr_value|
self.instance_variable_set '@'+attr_name.to_s, attr_value
end
return self
end
def id
@_id
end
def ==(other)
self.id == other.id
end
module ClassMethods
attr_accessor :collection
def create(params)
new_object = new(params)
new_object.save
return new_object
end
def index(key_name, options={})
return if Util.blank?(key_name)
method_name = 'find_by_'+(options[:as] or key_name).to_s
if viable_method_name(method_name)
(class << self; self; end).class_eval do
define_method method_name.to_sym do |value|
collection.find(key_name.to_sym => value).map{|bson_hash| new(bson_hash)}
end
end
end
collection.create_index(key_name)
end
def find(query=nil)
query = {'_id' => query} unless query.nil? or query.is_a?(Hash)
collection.find(query).map{|bson_hash| new(bson_hash)}
end
def viable_method_name(method_name)
method_name =~ /^\w+[!?]?$/
end
end
end
end
end