beanbag 0.1.0 → 0.1.1
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/beanbag.rb +37 -20
- metadata +2 -2
data/lib/beanbag.rb
CHANGED
@@ -2,40 +2,57 @@ require 'couchrest'
|
|
2
2
|
|
3
3
|
class BeanBag
|
4
4
|
|
5
|
+
@db_name = ''
|
6
|
+
@database = nil
|
7
|
+
|
5
8
|
def initialize(args)
|
6
9
|
@data = args
|
7
10
|
end
|
8
11
|
|
9
|
-
|
12
|
+
def self.in_database(db_name)
|
13
|
+
@db_name = db_name
|
14
|
+
end
|
15
|
+
|
16
|
+
def self.found_by(*identifiers)
|
10
17
|
|
11
|
-
|
18
|
+
@identifiers = {}
|
12
19
|
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
@@criteria[criteria] = nil
|
21
|
-
end
|
20
|
+
identifiers.each do |id|
|
21
|
+
if id.is_a? Hash
|
22
|
+
@identifiers = @identifiers.merge id
|
23
|
+
elsif id.is_a? String or id.is_a? Symbol
|
24
|
+
@identifiers[id] = nil
|
25
|
+
end
|
26
|
+
end
|
22
27
|
end
|
23
28
|
|
29
|
+
def self.design_doc
|
30
|
+
design_doc_name = "_design/#{self.name.downcase}"
|
31
|
+
begin
|
32
|
+
doc = database.get(design_doc_name)
|
33
|
+
rescue RestClient::ResourceNotFound
|
34
|
+
doc = CouchRest::Document.new("views" => {})
|
35
|
+
doc.id = design_doc_name
|
36
|
+
database.save_doc(doc)
|
37
|
+
retry
|
38
|
+
end
|
39
|
+
doc
|
40
|
+
end
|
41
|
+
|
24
42
|
def self.all
|
25
43
|
begin
|
26
44
|
view sprintf('%s/all_%ss', self.name.downcase, self.name.downcase)
|
27
|
-
rescue
|
28
|
-
|
29
|
-
doc = database.get("_design/#{self.name.downcase}")
|
45
|
+
rescue RestClient::ResourceNotFound
|
46
|
+
doc = design_doc
|
30
47
|
doc['views']["all_#{self.name.downcase}s"] = {}
|
31
48
|
|
32
49
|
view_string = "function(doc){"
|
33
|
-
if not
|
50
|
+
if not @identifiers.empty?
|
34
51
|
view_string << "if("
|
35
52
|
conditions = []
|
36
|
-
|
53
|
+
@identifiers.each_pair do |name, value|
|
37
54
|
conditions << "doc.#{name.to_s}"
|
38
|
-
|
55
|
+
conditions << "doc.#{name.to_s} === '#{value.to_s}'" if not value.nil?
|
39
56
|
end
|
40
57
|
view_string << conditions.join(" && ")
|
41
58
|
view_string << ")"
|
@@ -49,10 +66,10 @@ class BeanBag
|
|
49
66
|
end
|
50
67
|
|
51
68
|
def self.database
|
52
|
-
if not defined?
|
53
|
-
|
69
|
+
if not defined? @database
|
70
|
+
@database = CouchRest.new.database(@db_name)
|
54
71
|
end
|
55
|
-
|
72
|
+
@database
|
56
73
|
end
|
57
74
|
|
58
75
|
def self.view(view_name)
|