public
Fork of chuyeow/activecouch
Description: ActiveCouch is a simple, convenient, Ruby-idiomatic wrapper for CouchDB
Homepage: http://github.com/arunthampi/activecouch
Clone URL: git://github.com/arunthampi/activecouch.git
Search Repo:
- Re-organize in gem-friendly layout
- Added Rakefile for gem building
- Much more verbose README
- Added CY to license (sorry forgot!)
arunthampi (author)
Wed Jan 23 01:04:42 -0800 2008
commit  9e6e7a363b02c8ec9bf35d7acbfe201fc467b37f
tree    a9e7722bdf62dbc810c41e1deb6357833fd437be
parent  16551af40cbab57796359196801a1500df3b9a11
...
1
 
2
3
4
...
 
1
2
3
4
0
@@ -1,4 +1,4 @@
0
-Copyright (c) 2007 Arun Thampi
0
+Copyright (c) 2007 Arun Thampi & Cheah Chu Yeow
0
 
0
 Permission is hereby granted, free of charge, to any person obtaining
0
 a copy of this software and associated documentation files (the
0
...
1
 
2
3
4
5
6
7
 
 
 
8
9
10
11
 
 
 
12
13
14
15
16
 
 
 
 
 
 
 
17
18
19
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
...
 
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
0
@@ -1,21 +1,43 @@
0
-ActiveCouch aims to be an easy-to-use, familiar ORM library for the hot new kid on the block, CouchDB.
0
+ActiveCouch wants to be a simple, convenient, idiomatic Object Relational Mapper for the hot new kid on the block - CouchDB. CouchDB (simplistically speaking) is a document store, which essentially means that objects can be stored in a schema-less environment.
0
 
0
-* Preliminarily,
0
-- it will support ActiveRecord-esque functions such as find, create, save, etc.
0
-- location of the CouchDB will be specified through a very simple class method called 'site' similar to ActiveResource.
0
-- callbacks and observers (for example when to call upon saving of a new document)
0
-- migrations to add views to a CouchDB server
0
+What it is?
0
+-----------
0
+With ActiveCouch, you can easily save, query, delete documents to/from a CouchDB database in your favourite language - Ruby. ActiveCouch derives a lot of its principles (and some code) from both ActiveRecord and ActiveResource, two libraries made popular by the other hot pubescent on the block - Ruby on Rails (http://www.rubyonrails.org).
0
 
0
-* Nodes supported:
0
-- String, Integer, Float (E.g. has :name)
0
-- array (E.g. has_many :airports)
0
+Why?
0
+----
0
+As they say, necessity is the mother of invention. And as they also say, death before inconvenience. Our company, Bezurk (http://www.bezurk.com) is experimenting with CouchDB as we have a need for a document-model to store vast amounts of information, and we needed a convenience mapper in our favourite language, in order to use CouchDB elegantly. Since, the Rubyists here at Bezurk are already very familiar with ActiveRecord semantics, care has been taken to ensure that ActiveCouch resembled it in many ways.
0
 
0
-Pre-requisites
0
---------------
0
-- Ruby 1.8.5 (http://www.ruby-lang.org)
0
-- Uses JSON gem (http://json.rubyforge.org), To install use gem install json)
0
+Requirements
0
+------------
0
+ - Ruby 1.8.5 or above (http://www.ruby-lang.org)
0
+ - rubygems 0.9.4 (http://rubygems.org)
0
+ - JSON gem (http://json.rubyforge.org) [Used for JSON encoding/decoding]
0
+ - RSpec gem (http://rspec.rubyforge.org) [Used to run specs]
0
+ - CouchDB 0.7.2 (http://couchdb.googlecode.com) [Some specs require running CouchDB at localhost:5984]
0
 
0
-To run specs (and thus look at code samples)
0
---------------------------------------------
0
-- Install rspec gem (http://rspec.rubyforge.org, to install use gem install rspec)
0
+We would also recommend installing ZenTest (http://www.zenspider.com/ZSS/Products/ZenTest/) which provides a very convenient way to run specs.
0
+
0
+Show me the docs
0
+----------------
0
+We have some pretty basic RDoc bundled along with the source code. But the best source of documentation and sample code at this point will be the specs. The layout for specs has been inspired from the very inspiring Rubinius project (http://rubini.us) where each class has its own directory, and each method has its own spec file, thus making it very readable.
0
+
0
+
0
+Show me the code
0
+----------------
0
+SVN Repo is here: http://activecouch.googlecode.com/svn/trunk/
0
+
0
+Bugs/Issues
0
+-----------
0
+If and when you find bugs/feature requests, please raise a ticket at http://activecouch.googlecode.com . If we find that feature requests are crucial for our internal use, we will definitely integrate it into our project as soon as possible. But otherwise, we unfortunately cannot guarantee any deadlines on integration of feature requests. [http://www.flickr.com/photos/rooreynolds/243810133/]
0
+
0
+So, if you find bugs/feature requests, we'd greatly appreciate patches (which include specs), but otherwise please bear with us.
0
+
0
+
0
+Looking Forward
0
+---------------
0
+
0
+Obviously, we are very excited about developments in CouchDB land and we will be closely monitoring the CouchDB project, in order to further improve ActiveCouch. Since we are using ActiveCouch internally, we are expecting heavy development in CouchDB in the months to come.
0
+
0
+"The Journey is the Reward"
...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
...
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
0
@@ -1 +1,32 @@
0
+require 'rubygems'
0
+require 'rake/gempackagetask'
0
+
0
+PKG_VERSION = File.read('VERSION').chomp
0
+PKG_FILES = FileList[
0
+ '[A-Z]*',
0
+ 'lib/**/*.rb',
0
+ 'spec/**/*.rb'
0
+]
0
+
0
+spec = Gem::Specification.new do |s|
0
+ s.platform = Gem::Platform::RUBY
0
+ s.summary = "Ruby-based wrapper for CouchDB"
0
+ s.name = 'activecouch'
0
+ s.author = 'Arun Thampi & Cheah Chu Yeow'
0
+ s.email = "arun.thampi@gmail.com, chuyeow@gmail.com"
0
+ s.homepage = "http://activecouch.googlecode.com"
0
+ s.version = PKG_VERSION
0
+ s.files = PKG_FILES
0
+ s.has_rdoc = true
0
+ s.require_path = "lib"
0
+ s.extra_rdoc_files = ["README"]
0
+ s.add_dependency 'json', '>=1.1.2'
0
+end
0
+
0
+Rake::GemPackageTask.new(spec) do |pkg|
0
+ pkg.need_zip = true
0
+ pkg.need_tar = true
0
+end
0
+
0
+task :default => [:package]
...
 
...
1
0
@@ -1 +1,2 @@
0
+0.1.0
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0
@@ -1,19 +1 @@
0
-$:.unshift(File.dirname(__FILE__)) unless
0
- $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
0
-
0
-require 'rubygems'
0
-require 'json'
0
-
0
-require 'active_couch/attribute'
0
-require 'active_couch/associations'
0
-require 'active_couch/support'
0
-require 'active_couch/errors'
0
-require 'active_couch/base'
0
-require 'active_couch/connection'
0
-require 'active_couch/migrations'
0
-require 'active_couch/callbacks'
0
-
0
-#ActiveCouch::Base.class_eval do
0
-# include ActiveCouch::Callbacks
0
-#end
...
1
...
 
0
@@ -1,2 +1 @@
0
-require 'active_couch/associations/has_many_association'
...
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
...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0
@@ -1,36 +1 @@
0
-# TODO Consider implementing Enumerable semantics.
0
-
0
-module ActiveCouch
0
- class HasManyAssociation
0
- attr_accessor :name, :klass, :container
0
-
0
- def initialize(name, options = {})
0
- @name, @container, klass = name.to_s, [], options[:class]
0
- if !klass.nil? && klass.is_a?(Class)
0
- @klass = klass
0
- else
0
- # Use the inflector to get the correct class if it is not defined
0
- # in the :class key in the options hash
0
- # so has_many :contacts (will try to find the class Contact and set it to @klass)
0
- @klass = Inflector.constantize(Inflector.classify(@name))
0
- end
0
- end
0
-
0
- def push(obj)
0
- unless obj.is_a?(klass)
0
- raise InvalidCouchTypeError, "The object that you are trying to add is not a #{klass}"
0
- end
0
- @container << obj
0
- end
0
-
0
- def pop
0
- @container.pop
0
- end
0
-
0
- def to_hash
0
- { @name => @container }
0
- end
0
-
0
- end
0
-end
...
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
...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0
@@ -1,47 +1 @@
0
-module ActiveCouch
0
- class Attribute
0
- attr_reader :name, :klass, :value
0
- TYPES = {:decimal => Float, :text => String, :number => Integer}
0
- DEFAULTS = {:decimal => 0.0, :text => "", :number => 0}
0
-
0
- def initialize(name, options = {})
0
- klass, value = String, ""
0
- # Check for types supported
0
- if options.has_key?(:which_is)
0
- type = options[:which_is]
0
- unless type == :decimal || type == :number || type == :text
0
- raise InvalidCouchTypeError, "Types must be either decimal, number or text"
0
- else
0
- klass = TYPES[type]; value = DEFAULTS[type]
0
- end
0
- end
0
- # Check if default value provided matches the type provided
0
- if options.has_key?(:with_default_value)
0
- value = options[:with_default_value]
0
- unless value.is_a?(klass) || value.is_a?(NilClass)
0
- raise InvalidCouchTypeError, "Default value provided does not match the type of #{klass.to_s}"
0
- end
0
- end
0
- # Set the value, defaults to empty String
0
- @value, @klass, @name = value, klass, name.to_s
0
- end
0
-
0
- def value=(val)
0
- unless val.is_a?(@klass) || val.is_a?(NilClass)
0
- raise InvalidCouchTypeError, "Default value provided does not match the type of #{@klass.to_s}"
0
- end
0
- # Set the value if value matches type
0
- @value = val
0
- end
0
-
0
- def to_hash
0
- { @name => @value }
0
- end
0
-
0
- def nil?
0
- @value.nil?
0
- end
0
-
0
- end # End class CouchAttribute
0
-end # End module ActiveCouch
...
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0
@@ -1,459 +1 @@
0
-module ActiveCouch
0
- class Base
0
- SPECIAL_MEMBERS = %w(attributes associations connection callbacks)
0
- DEFAULT_ATTRIBUTES = %w(id rev)
0
-
0
- def initialize(params = {})
0
- # Object instance variable
0
- @attributes = {}; @associations = {}; @callbacks = Hash.new; @connection = self.class.connection
0
- klass_atts = self.class.attributes; klass_assocs = self.class.associations; klass_callbacks = self.class.callbacks
0
- # ActiveCouch::Connection object will be readable in every
0
- # object instantiated from a subclass of ActiveCouch::Base
0
- SPECIAL_MEMBERS.each do |k|
0
- self.instance_eval "def #{k}; @#{k}; end"
0
- end
0
-
0
- klass_atts.each_key do |k|
0
- @attributes[k] = klass_atts[k].dup
0
- self.instance_eval "def #{k}; attributes[:#{k}].value; end"
0
- self.instance_eval "def #{k}=(val); attributes[:#{k}].value = val; end"
0
- end
0
-
0
- klass_assocs.each_key do |k|
0
- @associations[k] = HasManyAssociation.new(klass_assocs[k].name, :class => klass_assocs[k].klass)
0
- self.instance_eval "def #{k}; associations[:#{k}].container; end"
0
- # If you have has_many :people, this will add a method called add_person to the object instantiated
0
- # from the class
0
- self.instance_eval "def add_#{Inflector.singularize(k)}(val); associations[:#{k}].push(val); end"
0
- end
0
-
0
- klass_callbacks.each_key do |k|
0
- @callbacks[k] = klass_callbacks[k].dup
0
- end
0
-
0
- DEFAULT_ATTRIBUTES.each do |x|
0
- self.instance_eval "def #{x}; _#{x}; end"
0
- self.instance_eval "def #{x}=(val); self._#{x}=(val); end"
0
- end
0
-
0
- # Set any instance variables if any, which are present in the params hash
0
- from_hash(params)
0
- end
0
-
0
- # Generates a JSON representation of an instance of a subclass of ActiveCouch::Base.
0
- # Ignores attributes which have a nil value.
0
- #
0
- # Examples:
0
- # class Person < ActiveCouch::Base
0
- # has :name, :which_is => :text, :with_default_value => "McLovin"
0
- # end
0
- #
0
- # person = Person.new
0
- # person.to_json # {"name":"McLovin"}
0
- #
0
- # class AgedPerson < ActiveCouch::Base
0
- # has :age, :which_is => :decimal, :with_default_value => 3.5
0
- # end
0
- #
0
- # aged_person = AgedPerson.new
0
- # aged_person.id = 'abc-def'
0
- # aged_person.to_json # {"age":3.5, "_id":"abc-def"}
0
- def to_json
0
- hash = {}
0
-
0
- attributes.each_value { |v| hash.merge!(v.to_hash) unless v.nil? }
0
- associations.each_value { |v| hash.merge!(v.to_hash) }
0
- # and by the Power of Grayskull, convert the hash to json
0
- hash.to_json
0
- end
0
-
0
- # Saves a document into a CouchDB database. A document can be saved in two ways.
0
- # One if it has been set an ID by the user, in which case the connection object
0
- # needs to use an HTTP PUT request to the URL /database/user_generated_id.
0
- # For the document needs a CouchDB-generated ID, the connection object needs
0
- # to use an HTTP POST request to the URL /database.
0
- #
0
- # Examples:
0
- # class Person < ActiveCouch::Base
0
- # has :name, :which_is => :text
0
- # end
0
- #
0
- # person = Person.new(:name => 'McLovin')
0
- # person.id = 'abc'
0
- # person.save # true
0
- # person.new? # false
0
- def save
0
- if id
0
- response = connection.put("/#{self.class.database_name}/#{id}", to_json)
0
- else
0
- response = connection.post("/#{self.class.database_name}", to_json)
0
- end
0
- # Parse the JSON obtained from the body...
0
- results = JSON.parse(response.body)
0
- # ...and set the default id and rev attributes
0
- DEFAULT_ATTRIBUTES.each { |a| self.__send__("#{a}=", results[a]) }
0
- # Response sent will be 201, if the save was successful [201 corresponds to 'created']
0
- return response.code == '201'
0
- end
0
-
0
- # Checks to see if a document has been persisted in a CouchDB database.
0
- # If a document has been retrieved from CouchDB, or has been persisted in
0
- # a CouchDB database, the attribute _rev would not be nil.
0
- #
0
- # Examples:
0
- # class Person < ActiveCouch::Base
0
- # has :name, :which_is => :text
0
- # end
0
- #
0
- # person = Person.new(:name => 'McLovin')
0
- # person.id = 'abc'
0
- # person.save # true
0
- # person.new? # false
0
- def new?
0
- rev.nil?
0
- end
0
-
0
- # Deletes a document from a CouchDB database. This is an instance-level delete method.
0
- # Example:
0
- # class Person < ActiveCouch::Base
0
- # has :name
0
- # end
0
- #
0
- # person = Person.create(:name => 'McLovin')
0
- # person.delete # true
0
- def delete
0
- if new?
0
- raise ArgumentError, "You must specify a revision for the document to be deleted"
0
- elsif id.nil?
0
- raise ArgumentError, "You must specify an ID for the document to be deleted"
0
- end
0
- response = connection.delete("/#{self.class.database_name}/#{id}?rev=#{rev}")
0
- # Set the id and rev to nil, since the object has been successfully deleted from CouchDB
0
- if response.code == '202'
0
- self.id = nil; self.rev = nil
0
- true
0
- else
0
- false
0
- end
0
- end
0
-
0
- class << self # Class methods
0
-
0
- # Returns the CouchDB database name that's backing this model. The database name is guessed from the name of the
0
- # class somewhat similar to ActiveRecord conventions.
0
- #
0
- # Examples:
0
- # class Invoice < ActiveCouch::Base; end;
0
- # file class database_name
0
- # invoice.rb Invoice invoices
0
- #
0
- # class Invoice < ActiveCouch::Base; class Lineitem < ActiveCouch::Base; end; end;
0
- # file class database_name
0
- # invoice.rb Invoice::Lineitem invoice_lineitems
0
- #
0
- # module Invoice; class Lineitem < ActiveCouch::Base; end; end;
0
- # file class database_name
0
- # invoice/lineitem.rb Invoice::Lineitem lineitems
0
- #
0
- # You can override this method or use <tt>set_database_name</tt> to override this class method to allow for names
0
- # that can't be inferred.
0
- def database_name
0
- base = base_class
0
- name = (unless self == base
0
- base.database_name
0
- else
0
- # Nested classes are prefixed with singular parent database name.
0
- if parent < ActiveCouch::Base
0
- contained = Inflector.singularize(parent.database_name)
0
- contained << '_'
0
- end
0
- "#{contained}#{Inflector.underscore(Inflector.demodulize(Inflector.pluralize(base.name)))}"
0
- end)
0
- set_database_name(name)
0
- name
0
- end
0
-
0
- # Sets the database name to the given value, or (if the value is nil or false) to the value returned by the
0
- # given block. Useful for setting database names that can't be automatically inferred from the class name.
0
- #
0
- # This method is aliased as <tt>database_name=</tt>.
0
- #
0
- # Example:
0
- #
0
- # class Post < ActiveCouch::Base
0
- # set_database_name 'legacy_posts'
0
- # end
0
- def set_database_name(database = nil, &block)
0
- define_attr_method(:database_name, database, &block)
0
- end
0
- alias :database_name= :set_database_name
0
-
0
- # Sets the site which the ActiveCouch object has to connect to, which
0
- # initializes an ActiveCouch::Connection object.
0
- #
0
- # Example:
0
- # class Person < ActiveCouch::Base
0
- # site 'localhost:5984'
0
- # end
0
- #
0
- # Person.connection.nil? # false
0
- def site(site)
0
- @connection = Connection.new(site)
0
- end
0
-
0
- # Defines an attribute for a subclass of ActiveCouch::Base. The parameters
0
- # for this method include name, which is the name of the attribute as well as
0
- # an options hash.
0
- #
0
- # The options hash can contain the key 'which_is' which can
0
- # have possible values :text, :decimal, :number. It can also contain the key
0
- # 'with_default_value' which can set a default value for each attribute defined
0
- # in the subclass of ActiveCouch::Base
0
- #
0
- # Examples:
0
- # class Person < ActiveCouch::Base
0
- # has :name
0
- # end
0
- #
0
- # person = Person.new
0
- # p.name.methods.include?(:name) # true
0
- # p.name.methods.include?(:name=) # false
0
- #
0
- # class AgedPerson < ActiveCouch::Base
0
- # has :age, :which_is => :number, :with_default_value = 18
0
- # end
0
- #
0
- # person = AgedPerson.new
0
- # person.age # 18
0
- def has(name, options = {})
0
- unless name.is_a?(String) || name.is_a?(Symbol)
0
- raise ArgumentError, "#{name} is neither a String nor a Symbol"
0
- end
0
- @attributes[name] = Attribute.new(name, options)
0
- end
0
-
0
- # Defines an array of objects which are 'children' of this class. The has_many
0
- # function guesses the class of the child, based on the name of the association,
0
- # but can be over-ridden by the :class key in the options hash.
0
- #
0
- # Examples:
0
- #
0
- # class Person < ActiveCouch::Base
0
- # has :name
0
- # end
0
- #
0
- # class GrandPerson < ActiveCouch::Base
0
- # has_many :people # which will create an empty array which can contain
0
- # # Person objects
0
- # end
0
- def has_many(name, options = {})
0
- unless name.is_a?(String) || name.is_a?(Symbol)
0
- raise ArgumentError, "#{name} is neither a String nor a Symbol"
0
- end
0
- @associations[name] = HasManyAssociation.new(name, options)
0
- end
0
-
0
- # Initializes an object of a subclass of ActiveCouch::Base based on a JSON
0
- # representation of the object.
0
- #
0
- # Example:
0
- # class Person < ActiveCouch::Base
0
- # has :name
0
- # end
0
- #
0
- # person = Person.from_json('{"name":"McLovin"}')
0
- # person.name # "McLovin"
0
- def from_json(json)
0
- hash = JSON.parse(json)
0
- # Create new based on parsed
0
- self.new(hash)
0
- end
0
-
0
- # Retrieves one or more object(s) from a CouchDB database, based on the search
0
- # parameters given.
0
- #
0
- # Example:
0
- # class Person < ActiveCouch::Base
0
- # has :name
0
- # end
0
- #
0
- # # This returns a single instance of an ActiveCouch::Base subclass
0
- # people = Person.find(:first, :params => {:name => "McLovin"})
0
- #
0
- # # This returns an array of ActiveCouch::Base subclass instances
0
- # person = Person.find(:all, :params => {:name => "McLovin"})
0
- def find(*arguments)
0
- scope = arguments.slice!(0)
0
- options = arguments.slice!(0) || {}
0
-
0
- case scope
0
- when :all then find_every(options)
0
- when :first then find_every(options).first
0
- else raise ArgumentError("find must have the first parameter as either :all or :first")
0
- end
0
- end
0
-
0
- # Initializes a new subclass of ActiveCouch::Base and saves in the CouchDB database
0
- # as a new document
0
- #
0
- # Example:
0
- # class Person < ActiveCouch::Base
0
- # has :name
0
- # end
0
- #
0
- # person = Person.create(:name => "McLovin")
0
- # person.id.nil? # false
0
- # person.new? # false
0
- def create(arguments)
0
- unless arguments.is_a?(Hash)
0
- raise ArgumentError, "The arguments must be a Hash"
0
- else
0
- new_record = self.new(arguments)
0
- new_record.save
0
- new_record
0
- end
0
- end
0
-
0
- # Deletes a document from the CouchDB database, based on the id and rev parameters passed to it.
0
- # Returns true if the document has been deleted
0
- #
0
- # Example:
0
- # class Person < ActiveCouch::Base
0
- # has :name
0
- # end
0
- #
0
- # Person.delete(:id => 'abc-def', :rev => '1235')
0
- def delete(options = {})
0
- if options.nil? || !options.has_key?(:id) || !options.has_key?(:rev)
0
- raise ArgumentError, "You must specify both an id and a rev for the document to be deleted"
0
- end
0
- response = connection.delete("/#{self.database_name}/#{options[:id]}?rev=#{options[:rev]}")
0
- # Returns true if the
0
- response.code == '202'
0
- end
0
-
0
- # Defines an "attribute" method. A new (class) method will be created with the
0
- # given name. If a value is specified, the new method will
0
- # return that value (as a string). Otherwise, the given block
0
- # will be used to compute the value of the method.
0
- #
0
- # The original method, if it exists, will be aliased, with the
0
- # new name being
0
- # prefixed with "original_". This allows the new method to
0
- # access the original value.
0
- #
0
- # This method is stolen from ActiveRecord.
0
- #
0
- # Example:
0
- #
0
- # class Foo < ActiveCouch::Base
0
- # define_attr_method :database_name, 'foo'
0
- # # OR
0
- # define_attr_method(:database_name) do
0
- # original_database_name + '_legacy'
0
- # end
0
- # end
0
- def define_attr_method(name, value = nil, &block)
0
- metaclass.send(:alias_method, "original_#{name}", name)
0
- if block_given?
0
- meta_def name, &block
0
- else
0
- metaclass.class_eval "def #{name}; #{value.to_s.inspect}; end"
0
- end
0
- end
0
-
0
- def inherited(subklass)
0
- subklass.class_eval do
0
- include ActiveCouch::Callbacks
0
- end
0
-
0
- # TODO: Need a cleaner way to do this
0
- subklass.instance_variable_set "@attributes", { :_id => Attribute.new(:_id, :with_default_value => nil),
0
- :_rev => Attribute.new(:_rev, :with_default_value => nil) }
0
- subklass.instance_variable_set "@associations", {}
0
- subklass.instance_variable_set "@callbacks", Hash.new([])
0
- subklass.instance_variable_set "@connections", nil
0
-
0
- SPECIAL_MEMBERS.each do |k|
0
- subklass.instance_eval "def #{k}; @#{k}; end"
0
- end
0
- end
0
-
0
- def base_class
0
- class_of_active_couch_descendant(self)
0
- end
0
-
0
- private
0
-
0
- # Returns the class descending directly from ActiveCouch in the inheritance hierarchy.
0
- def class_of_active_couch_descendant(klass)
0
- if klass.superclass == Base
0
- klass
0
- elsif klass.superclass.nil?
0
- raise ActiveCouchError, "#{name} doesn't belong in a hierarchy descending from ActiveCouch"
0
- else
0
- class_of_active_couch_descendant(klass.superclass)
0
- end
0
- end
0
-
0
- # Returns an array of ActiveCouch::Base objects by querying a CouchDB permanent view
0
- def find_every(options)
0
- case from = options[:from]
0
- when String
0
- path = "#{from}"
0
- else
0
- path = "/#{database_name}/_view/#{query_string(options[:params])}"
0
- end
0
- instantiate_collection(connection.get(path))
0
- end
0
-
0
- # Generates a query string by using the ActiveCouch convention, which is to
0
- # have the view defined by pre-pending the attribute to be queried with 'by_'
0
- # So for example, if the params hash is :name => 'McLovin',
0
- # the view associated with it will be /by_name/by_name?key="McLovin"
0
- def query_string(params)
0
- if params.is_a?(Hash)
0
- params.each { |k,v| return "by_#{k}/by_#{k}?key=#{v.url_encode}" }
0
- else
0
- raise ArgumentError, "The value for the key 'params' must be a Hash"
0
- end
0
- end
0
-
0
- # Instantiates a collection of ActiveCouch::Base objects, based on the
0
- # result obtained from a CouchDB View.
0
- #
0
- # As per the CouchDB Permanent View API, the result set will be contained
0
- # within a JSON hash as an array, with the key 'rows'
0
- # The actual CouchDB object which needs to be initialized is obtained with
0
- # the key 'value'
0
- def instantiate_collection(result)
0
- hash = JSON.parse(result)
0
- hash['rows'].collect { |row| self.new(row['value']) }
0
- end
0
- end # End class methods
0
-
0
- private
0
- def from_hash(hash)
0
- # TODO:
0
- # - Clean this up. Doesn't look very nice
0
- # - Raise errors if attribute/association is not present
0
- hash.each do |k,v|
0
- k = k.to_sym rescue k
0
- if v.is_a?(Array) # This means this is a has_many association
0
- unless (assoc = @associations[k]).nil?
0
- name, child_klass = assoc.name, assoc.klass
0
- v.each do |child|
0
- child.is_a?(Hash) ? child_obj = child_klass.new(child) : child_obj = child
0
- self.send "add_#{Inflector.singularize(name)}", child_obj
0
- end
0
- end
0
- elsif v.is_a?(Hash) # This means this is a has_one association (which we might add later)
0
- # Do nothing for now. More later
0
- else # This means this is a normal attribute
0
- self.send("#{k}=", v) if respond_to?("#{k}=") # @attributes.has_key?(k) || @attributes.has_key?("_#{k}")
0
- end
0
- end
0
- end
0
- end # End class Base
0
-end # End module ActiveCouch