activecouch 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (52) hide show
  1. data/MIT-LICENSE +20 -0
  2. data/README +42 -0
  3. data/Rakefile +31 -0
  4. data/VERSION +1 -0
  5. data/lib/active_couch.rb +18 -0
  6. data/lib/active_couch/associations.rb +1 -0
  7. data/lib/active_couch/associations/has_many_association.rb +35 -0
  8. data/lib/active_couch/attribute.rb +46 -0
  9. data/lib/active_couch/base.rb +458 -0
  10. data/lib/active_couch/callbacks.rb +81 -0
  11. data/lib/active_couch/connection.rb +155 -0
  12. data/lib/active_couch/errors.rb +17 -0
  13. data/lib/active_couch/migrations.rb +3 -0
  14. data/lib/active_couch/migrations/errors.rb +4 -0
  15. data/lib/active_couch/migrations/migration.rb +77 -0
  16. data/lib/active_couch/migrations/migrator.rb +53 -0
  17. data/lib/active_couch/support.rb +2 -0
  18. data/lib/active_couch/support/extensions.rb +92 -0
  19. data/lib/active_couch/support/inflections.rb +52 -0
  20. data/lib/active_couch/support/inflector.rb +280 -0
  21. data/spec/attribute/initialize_spec.rb +138 -0
  22. data/spec/base/after_delete_spec.rb +107 -0
  23. data/spec/base/after_save_spec.rb +99 -0
  24. data/spec/base/before_delete_spec.rb +106 -0
  25. data/spec/base/before_save_spec.rb +98 -0
  26. data/spec/base/create_spec.rb +27 -0
  27. data/spec/base/database_spec.rb +65 -0
  28. data/spec/base/delete_spec.rb +78 -0
  29. data/spec/base/find_spec.rb +165 -0
  30. data/spec/base/from_json_spec.rb +48 -0
  31. data/spec/base/has_many_spec.rb +81 -0
  32. data/spec/base/has_spec.rb +76 -0
  33. data/spec/base/id_spec.rb +22 -0
  34. data/spec/base/initialize_spec.rb +43 -0
  35. data/spec/base/module_spec.rb +18 -0
  36. data/spec/base/nested_class_spec.rb +19 -0
  37. data/spec/base/rev_spec.rb +16 -0
  38. data/spec/base/save_spec.rb +65 -0
  39. data/spec/base/site_spec.rb +41 -0
  40. data/spec/base/to_json_spec.rb +64 -0
  41. data/spec/connection/initialize_spec.rb +28 -0
  42. data/spec/has_many_association/initialize_spec.rb +33 -0
  43. data/spec/migration/define_spec.rb +29 -0
  44. data/spec/migration/include_attributes_spec.rb +30 -0
  45. data/spec/migration/view_js_spec.rb +46 -0
  46. data/spec/migration/with_filter_spec.rb +13 -0
  47. data/spec/migration/with_key_spec.rb +13 -0
  48. data/spec/migrator/create_database_spec.rb +48 -0
  49. data/spec/migrator/delete_database_spec.rb +46 -0
  50. data/spec/migrator/migrate_spec.rb +99 -0
  51. data/spec/spec_helper.rb +9 -0
  52. metadata +104 -0
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2007 Arun Thampi & Cheah Chu Yeow
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1,42 @@
1
+ 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.
2
+
3
+ What it is?
4
+ -----------
5
+ 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).
6
+
7
+ Why?
8
+ ----
9
+ 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.
10
+
11
+ Requirements
12
+ ------------
13
+ - Ruby 1.8.5 or above (http://www.ruby-lang.org)
14
+ - rubygems 0.9.4 (http://rubygems.org)
15
+ - JSON gem (http://json.rubyforge.org) [Used for JSON encoding/decoding]
16
+ - RSpec gem (http://rspec.rubyforge.org) [Used to run specs]
17
+ - CouchDB 0.7.2 (http://couchdb.googlecode.com) [Some specs require running CouchDB at localhost:5984]
18
+
19
+ We would also recommend installing ZenTest (http://www.zenspider.com/ZSS/Products/ZenTest/) which provides a very convenient way to run specs.
20
+
21
+ Show me the docs
22
+ ----------------
23
+ 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.
24
+
25
+
26
+ Show me the code
27
+ ----------------
28
+ SVN Repo is here: http://activecouch.googlecode.com/svn/trunk/
29
+
30
+ Bugs/Issues
31
+ -----------
32
+ 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/]
33
+
34
+ So, if you find bugs/feature requests, we'd greatly appreciate patches (which include specs), but otherwise please bear with us.
35
+
36
+
37
+ Looking Forward
38
+ ---------------
39
+
40
+ 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.
41
+
42
+ "The Journey is the Reward"
@@ -0,0 +1,31 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+
4
+ PKG_VERSION = File.read('VERSION').chomp
5
+ PKG_FILES = FileList[
6
+ '[A-Z]*',
7
+ 'lib/**/*.rb',
8
+ 'spec/**/*.rb'
9
+ ]
10
+
11
+ spec = Gem::Specification.new do |s|
12
+ s.platform = Gem::Platform::RUBY
13
+ s.summary = "Ruby-based wrapper for CouchDB"
14
+ s.name = 'activecouch'
15
+ s.author = 'Arun Thampi & Cheah Chu Yeow'
16
+ s.email = "arun.thampi@gmail.com, chuyeow@gmail.com"
17
+ s.homepage = "http://activecouch.googlecode.com"
18
+ s.version = PKG_VERSION
19
+ s.files = PKG_FILES
20
+ s.has_rdoc = true
21
+ s.require_path = "lib"
22
+ s.extra_rdoc_files = ["README"]
23
+ s.add_dependency 'json', '>=1.1.2'
24
+ end
25
+
26
+ Rake::GemPackageTask.new(spec) do |pkg|
27
+ pkg.need_zip = true
28
+ pkg.need_tar = true
29
+ end
30
+
31
+ task :default => [:package]
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,18 @@
1
+ $:.unshift(File.dirname(__FILE__)) unless
2
+ $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
3
+
4
+ require 'rubygems'
5
+ require 'json'
6
+
7
+ require 'active_couch/attribute'
8
+ require 'active_couch/associations'
9
+ require 'active_couch/support'
10
+ require 'active_couch/errors'
11
+ require 'active_couch/base'
12
+ require 'active_couch/connection'
13
+ require 'active_couch/migrations'
14
+ require 'active_couch/callbacks'
15
+
16
+ #ActiveCouch::Base.class_eval do
17
+ # include ActiveCouch::Callbacks
18
+ #end
@@ -0,0 +1 @@
1
+ require 'active_couch/associations/has_many_association'
@@ -0,0 +1,35 @@
1
+ # TODO Consider implementing Enumerable semantics.
2
+
3
+ module ActiveCouch
4
+ class HasManyAssociation
5
+ attr_accessor :name, :klass, :container
6
+
7
+ def initialize(name, options = {})
8
+ @name, @container, klass = name.to_s, [], options[:class]
9
+ if !klass.nil? && klass.is_a?(Class)
10
+ @klass = klass
11
+ else
12
+ # Use the inflector to get the correct class if it is not defined
13
+ # in the :class key in the options hash
14
+ # so has_many :contacts (will try to find the class Contact and set it to @klass)
15
+ @klass = Inflector.constantize(Inflector.classify(@name))
16
+ end
17
+ end
18
+
19
+ def push(obj)
20
+ unless obj.is_a?(klass)
21
+ raise InvalidCouchTypeError, "The object that you are trying to add is not a #{klass}"
22
+ end
23
+ @container << obj
24
+ end
25
+
26
+ def pop
27
+ @container.pop
28
+ end
29
+
30
+ def to_hash
31
+ { @name => @container }
32
+ end
33
+
34
+ end
35
+ end
@@ -0,0 +1,46 @@
1
+ module ActiveCouch
2
+ class Attribute
3
+ attr_reader :name, :klass, :value
4
+ TYPES = {:decimal => Float, :text => String, :number => Integer}
5
+ DEFAULTS = {:decimal => 0.0, :text => "", :number => 0}
6
+
7
+ def initialize(name, options = {})
8
+ klass, value = String, ""
9
+ # Check for types supported
10
+ if options.has_key?(:which_is)
11
+ type = options[:which_is]
12
+ unless type == :decimal || type == :number || type == :text
13
+ raise InvalidCouchTypeError, "Types must be either decimal, number or text"
14
+ else
15
+ klass = TYPES[type]; value = DEFAULTS[type]
16
+ end
17
+ end
18
+ # Check if default value provided matches the type provided
19
+ if options.has_key?(:with_default_value)
20
+ value = options[:with_default_value]
21
+ unless value.is_a?(klass) || value.is_a?(NilClass)
22
+ raise InvalidCouchTypeError, "Default value provided does not match the type of #{klass.to_s}"
23
+ end
24
+ end
25
+ # Set the value, defaults to empty String
26
+ @value, @klass, @name = value, klass, name.to_s
27
+ end
28
+
29
+ def value=(val)
30
+ unless val.is_a?(@klass) || val.is_a?(NilClass)
31
+ raise InvalidCouchTypeError, "Default value provided does not match the type of #{@klass.to_s}"
32
+ end
33
+ # Set the value if value matches type
34
+ @value = val
35
+ end
36
+
37
+ def to_hash
38
+ { @name => @value }
39
+ end
40
+
41
+ def nil?
42
+ @value.nil?
43
+ end
44
+
45
+ end # End class CouchAttribute
46
+ end # End module ActiveCouch
@@ -0,0 +1,458 @@
1
+ module ActiveCouch
2
+ class Base
3
+ SPECIAL_MEMBERS = %w(attributes associations connection callbacks)
4
+ DEFAULT_ATTRIBUTES = %w(id rev)
5
+
6
+ def initialize(params = {})
7
+ # Object instance variable
8
+ @attributes = {}; @associations = {}; @callbacks = Hash.new; @connection = self.class.connection
9
+ klass_atts = self.class.attributes; klass_assocs = self.class.associations; klass_callbacks = self.class.callbacks
10
+ # ActiveCouch::Connection object will be readable in every
11
+ # object instantiated from a subclass of ActiveCouch::Base
12
+ SPECIAL_MEMBERS.each do |k|
13
+ self.instance_eval "def #{k}; @#{k}; end"
14
+ end
15
+
16
+ klass_atts.each_key do |k|
17
+ @attributes[k] = klass_atts[k].dup
18
+ self.instance_eval "def #{k}; attributes[:#{k}].value; end"
19
+ self.instance_eval "def #{k}=(val); attributes[:#{k}].value = val; end"
20
+ end
21
+
22
+ klass_assocs.each_key do |k|
23
+ @associations[k] = HasManyAssociation.new(klass_assocs[k].name, :class => klass_assocs[k].klass)
24
+ self.instance_eval "def #{k}; associations[:#{k}].container; end"
25
+ # If you have has_many :people, this will add a method called add_person to the object instantiated
26
+ # from the class
27
+ self.instance_eval "def add_#{Inflector.singularize(k)}(val); associations[:#{k}].push(val); end"
28
+ end
29
+
30
+ klass_callbacks.each_key do |k|
31
+ @callbacks[k] = klass_callbacks[k].dup
32
+ end
33
+
34
+ DEFAULT_ATTRIBUTES.each do |x|
35
+ self.instance_eval "def #{x}; _#{x}; end"
36
+ self.instance_eval "def #{x}=(val); self._#{x}=(val); end"
37
+ end
38
+
39
+ # Set any instance variables if any, which are present in the params hash
40
+ from_hash(params)
41
+ end
42
+
43
+ # Generates a JSON representation of an instance of a subclass of ActiveCouch::Base.
44
+ # Ignores attributes which have a nil value.
45
+ #
46
+ # Examples:
47
+ # class Person < ActiveCouch::Base
48
+ # has :name, :which_is => :text, :with_default_value => "McLovin"
49
+ # end
50
+ #
51
+ # person = Person.new
52
+ # person.to_json # {"name":"McLovin"}
53
+ #
54
+ # class AgedPerson < ActiveCouch::Base
55
+ # has :age, :which_is => :decimal, :with_default_value => 3.5
56
+ # end
57
+ #
58
+ # aged_person = AgedPerson.new
59
+ # aged_person.id = 'abc-def'
60
+ # aged_person.to_json # {"age":3.5, "_id":"abc-def"}
61
+ def to_json
62
+ hash = {}
63
+
64
+ attributes.each_value { |v| hash.merge!(v.to_hash) unless v.nil? }
65
+ associations.each_value { |v| hash.merge!(v.to_hash) }
66
+ # and by the Power of Grayskull, convert the hash to json
67
+ hash.to_json
68
+ end
69
+
70
+ # Saves a document into a CouchDB database. A document can be saved in two ways.
71
+ # One if it has been set an ID by the user, in which case the connection object
72
+ # needs to use an HTTP PUT request to the URL /database/user_generated_id.
73
+ # For the document needs a CouchDB-generated ID, the connection object needs
74
+ # to use an HTTP POST request to the URL /database.
75
+ #
76
+ # Examples:
77
+ # class Person < ActiveCouch::Base
78
+ # has :name, :which_is => :text
79
+ # end
80
+ #
81
+ # person = Person.new(:name => 'McLovin')
82
+ # person.id = 'abc'
83
+ # person.save # true
84
+ # person.new? # false
85
+ def save
86
+ if id
87
+ response = connection.put("/#{self.class.database_name}/#{id}", to_json)
88
+ else
89
+ response = connection.post("/#{self.class.database_name}", to_json)
90
+ end
91
+ # Parse the JSON obtained from the body...
92
+ results = JSON.parse(response.body)
93
+ # ...and set the default id and rev attributes
94
+ DEFAULT_ATTRIBUTES.each { |a| self.__send__("#{a}=", results[a]) }
95
+ # Response sent will be 201, if the save was successful [201 corresponds to 'created']
96
+ return response.code == '201'
97
+ end
98
+
99
+ # Checks to see if a document has been persisted in a CouchDB database.
100
+ # If a document has been retrieved from CouchDB, or has been persisted in
101
+ # a CouchDB database, the attribute _rev would not be nil.
102
+ #
103
+ # Examples:
104
+ # class Person < ActiveCouch::Base
105
+ # has :name, :which_is => :text
106
+ # end
107
+ #
108
+ # person = Person.new(:name => 'McLovin')
109
+ # person.id = 'abc'
110
+ # person.save # true
111
+ # person.new? # false
112
+ def new?
113
+ rev.nil?
114
+ end
115
+
116
+ # Deletes a document from a CouchDB database. This is an instance-level delete method.
117
+ # Example:
118
+ # class Person < ActiveCouch::Base
119
+ # has :name
120
+ # end
121
+ #
122
+ # person = Person.create(:name => 'McLovin')
123
+ # person.delete # true
124
+ def delete
125
+ if new?
126
+ raise ArgumentError, "You must specify a revision for the document to be deleted"
127
+ elsif id.nil?
128
+ raise ArgumentError, "You must specify an ID for the document to be deleted"
129
+ end
130
+ response = connection.delete("/#{self.class.database_name}/#{id}?rev=#{rev}")
131
+ # Set the id and rev to nil, since the object has been successfully deleted from CouchDB
132
+ if response.code == '202'
133
+ self.id = nil; self.rev = nil
134
+ true
135
+ else
136
+ false
137
+ end
138
+ end
139
+
140
+ class << self # Class methods
141
+
142
+ # Returns the CouchDB database name that's backing this model. The database name is guessed from the name of the
143
+ # class somewhat similar to ActiveRecord conventions.
144
+ #
145
+ # Examples:
146
+ # class Invoice < ActiveCouch::Base; end;
147
+ # file class database_name
148
+ # invoice.rb Invoice invoices
149
+ #
150
+ # class Invoice < ActiveCouch::Base; class Lineitem < ActiveCouch::Base; end; end;
151
+ # file class database_name
152
+ # invoice.rb Invoice::Lineitem invoice_lineitems
153
+ #
154
+ # module Invoice; class Lineitem < ActiveCouch::Base; end; end;
155
+ # file class database_name
156
+ # invoice/lineitem.rb Invoice::Lineitem lineitems
157
+ #
158
+ # You can override this method or use <tt>set_database_name</tt> to override this class method to allow for names
159
+ # that can't be inferred.
160
+ def database_name
161
+ base = base_class
162
+ name = (unless self == base
163
+ base.database_name
164
+ else
165
+ # Nested classes are prefixed with singular parent database name.
166
+ if parent < ActiveCouch::Base
167
+ contained = Inflector.singularize(parent.database_name)
168
+ contained << '_'
169
+ end
170
+ "#{contained}#{Inflector.underscore(Inflector.demodulize(Inflector.pluralize(base.name)))}"
171
+ end)
172
+ set_database_name(name)
173
+ name
174
+ end
175
+
176
+ # Sets the database name to the given value, or (if the value is nil or false) to the value returned by the
177
+ # given block. Useful for setting database names that can't be automatically inferred from the class name.
178
+ #
179
+ # This method is aliased as <tt>database_name=</tt>.
180
+ #
181
+ # Example:
182
+ #
183
+ # class Post < ActiveCouch::Base
184
+ # set_database_name 'legacy_posts'
185
+ # end
186
+ def set_database_name(database = nil, &block)
187
+ define_attr_method(:database_name, database, &block)
188
+ end
189
+ alias :database_name= :set_database_name
190
+
191
+ # Sets the site which the ActiveCouch object has to connect to, which
192
+ # initializes an ActiveCouch::Connection object.
193
+ #
194
+ # Example:
195
+ # class Person < ActiveCouch::Base
196
+ # site 'localhost:5984'
197
+ # end
198
+ #
199
+ # Person.connection.nil? # false
200
+ def site(site)
201
+ @connection = Connection.new(site)
202
+ end
203
+
204
+ # Defines an attribute for a subclass of ActiveCouch::Base. The parameters
205
+ # for this method include name, which is the name of the attribute as well as
206
+ # an options hash.
207
+ #
208
+ # The options hash can contain the key 'which_is' which can
209
+ # have possible values :text, :decimal, :number. It can also contain the key
210
+ # 'with_default_value' which can set a default value for each attribute defined
211
+ # in the subclass of ActiveCouch::Base
212
+ #
213
+ # Examples:
214
+ # class Person < ActiveCouch::Base
215
+ # has :name
216
+ # end
217
+ #
218
+ # person = Person.new
219
+ # p.name.methods.include?(:name) # true
220
+ # p.name.methods.include?(:name=) # false
221
+ #
222
+ # class AgedPerson < ActiveCouch::Base
223
+ # has :age, :which_is => :number, :with_default_value = 18
224
+ # end
225
+ #
226
+ # person = AgedPerson.new
227
+ # person.age # 18
228
+ def has(name, options = {})
229
+ unless name.is_a?(String) || name.is_a?(Symbol)
230
+ raise ArgumentError, "#{name} is neither a String nor a Symbol"
231
+ end
232
+ @attributes[name] = Attribute.new(name, options)
233
+ end
234
+
235
+ # Defines an array of objects which are 'children' of this class. The has_many
236
+ # function guesses the class of the child, based on the name of the association,
237
+ # but can be over-ridden by the :class key in the options hash.
238
+ #
239
+ # Examples:
240
+ #
241
+ # class Person < ActiveCouch::Base
242
+ # has :name
243
+ # end
244
+ #
245
+ # class GrandPerson < ActiveCouch::Base
246
+ # has_many :people # which will create an empty array which can contain
247
+ # # Person objects
248
+ # end
249
+ def has_many(name, options = {})
250
+ unless name.is_a?(String) || name.is_a?(Symbol)
251
+ raise ArgumentError, "#{name} is neither a String nor a Symbol"
252
+ end
253
+ @associations[name] = HasManyAssociation.new(name, options)
254
+ end
255
+
256
+ # Initializes an object of a subclass of ActiveCouch::Base based on a JSON
257
+ # representation of the object.
258
+ #
259
+ # Example:
260
+ # class Person < ActiveCouch::Base
261
+ # has :name
262
+ # end
263
+ #
264
+ # person = Person.from_json('{"name":"McLovin"}')
265
+ # person.name # "McLovin"
266
+ def from_json(json)
267
+ hash = JSON.parse(json)
268
+ # Create new based on parsed
269
+ self.new(hash)
270
+ end
271
+
272
+ # Retrieves one or more object(s) from a CouchDB database, based on the search
273
+ # parameters given.
274
+ #
275
+ # Example:
276
+ # class Person < ActiveCouch::Base
277
+ # has :name
278
+ # end
279
+ #
280
+ # # This returns a single instance of an ActiveCouch::Base subclass
281
+ # people = Person.find(:first, :params => {:name => "McLovin"})
282
+ #
283
+ # # This returns an array of ActiveCouch::Base subclass instances
284
+ # person = Person.find(:all, :params => {:name => "McLovin"})
285
+ def find(*arguments)
286
+ scope = arguments.slice!(0)
287
+ options = arguments.slice!(0) || {}
288
+
289
+ case scope
290
+ when :all then find_every(options)
291
+ when :first then find_every(options).first
292
+ else raise ArgumentError("find must have the first parameter as either :all or :first")
293
+ end
294
+ end
295
+
296
+ # Initializes a new subclass of ActiveCouch::Base and saves in the CouchDB database
297
+ # as a new document
298
+ #
299
+ # Example:
300
+ # class Person < ActiveCouch::Base
301
+ # has :name
302
+ # end
303
+ #
304
+ # person = Person.create(:name => "McLovin")
305
+ # person.id.nil? # false
306
+ # person.new? # false
307
+ def create(arguments)
308
+ unless arguments.is_a?(Hash)
309
+ raise ArgumentError, "The arguments must be a Hash"
310
+ else
311
+ new_record = self.new(arguments)
312
+ new_record.save
313
+ new_record
314
+ end
315
+ end
316
+
317
+ # Deletes a document from the CouchDB database, based on the id and rev parameters passed to it.
318
+ # Returns true if the document has been deleted
319
+ #
320
+ # Example:
321
+ # class Person < ActiveCouch::Base
322
+ # has :name
323
+ # end
324
+ #
325
+ # Person.delete(:id => 'abc-def', :rev => '1235')
326
+ def delete(options = {})
327
+ if options.nil? || !options.has_key?(:id) || !options.has_key?(:rev)
328
+ raise ArgumentError, "You must specify both an id and a rev for the document to be deleted"
329
+ end
330
+ response = connection.delete("/#{self.database_name}/#{options[:id]}?rev=#{options[:rev]}")
331
+ # Returns true if the
332
+ response.code == '202'
333
+ end
334
+
335
+ # Defines an "attribute" method. A new (class) method will be created with the
336
+ # given name. If a value is specified, the new method will
337
+ # return that value (as a string). Otherwise, the given block
338
+ # will be used to compute the value of the method.
339
+ #
340
+ # The original method, if it exists, will be aliased, with the
341
+ # new name being
342
+ # prefixed with "original_". This allows the new method to
343
+ # access the original value.
344
+ #
345
+ # This method is stolen from ActiveRecord.
346
+ #
347
+ # Example:
348
+ #
349
+ # class Foo < ActiveCouch::Base
350
+ # define_attr_method :database_name, 'foo'
351
+ # # OR
352
+ # define_attr_method(:database_name) do
353
+ # original_database_name + '_legacy'
354
+ # end
355
+ # end
356
+ def define_attr_method(name, value = nil, &block)
357
+ metaclass.send(:alias_method, "original_#{name}", name)
358
+ if block_given?
359
+ meta_def name, &block
360
+ else
361
+ metaclass.class_eval "def #{name}; #{value.to_s.inspect}; end"
362
+ end
363
+ end
364
+
365
+ def inherited(subklass)
366
+ subklass.class_eval do
367
+ include ActiveCouch::Callbacks
368
+ end
369
+
370
+ # TODO: Need a cleaner way to do this
371
+ subklass.instance_variable_set "@attributes", { :_id => Attribute.new(:_id, :with_default_value => nil),
372
+ :_rev => Attribute.new(:_rev, :with_default_value => nil) }
373
+ subklass.instance_variable_set "@associations", {}
374
+ subklass.instance_variable_set "@callbacks", Hash.new([])
375
+ subklass.instance_variable_set "@connections", nil
376
+
377
+ SPECIAL_MEMBERS.each do |k|
378
+ subklass.instance_eval "def #{k}; @#{k}; end"
379
+ end
380
+ end
381
+
382
+ def base_class
383
+ class_of_active_couch_descendant(self)
384
+ end
385
+
386
+ private
387
+
388
+ # Returns the class descending directly from ActiveCouch in the inheritance hierarchy.
389
+ def class_of_active_couch_descendant(klass)
390
+ if klass.superclass == Base
391
+ klass
392
+ elsif klass.superclass.nil?
393
+ raise ActiveCouchError, "#{name} doesn't belong in a hierarchy descending from ActiveCouch"
394
+ else
395
+ class_of_active_couch_descendant(klass.superclass)
396
+ end
397
+ end
398
+
399
+ # Returns an array of ActiveCouch::Base objects by querying a CouchDB permanent view
400
+ def find_every(options)
401
+ case from = options[:from]
402
+ when String
403
+ path = "#{from}"
404
+ else
405
+ path = "/#{database_name}/_view/#{query_string(options[:params])}"
406
+ end
407
+ instantiate_collection(connection.get(path))
408
+ end
409
+
410
+ # Generates a query string by using the ActiveCouch convention, which is to
411
+ # have the view defined by pre-pending the attribute to be queried with 'by_'
412
+ # So for example, if the params hash is :name => 'McLovin',
413
+ # the view associated with it will be /by_name/by_name?key="McLovin"
414
+ def query_string(params)
415
+ if params.is_a?(Hash)
416
+ params.each { |k,v| return "by_#{k}/by_#{k}?key=#{v.url_encode}" }
417
+ else
418
+ raise ArgumentError, "The value for the key 'params' must be a Hash"
419
+ end
420
+ end
421
+
422
+ # Instantiates a collection of ActiveCouch::Base objects, based on the
423
+ # result obtained from a CouchDB View.
424
+ #
425
+ # As per the CouchDB Permanent View API, the result set will be contained
426
+ # within a JSON hash as an array, with the key 'rows'
427
+ # The actual CouchDB object which needs to be initialized is obtained with
428
+ # the key 'value'
429
+ def instantiate_collection(result)
430
+ hash = JSON.parse(result)
431
+ hash['rows'].collect { |row| self.new(row['value']) }
432
+ end
433
+ end # End class methods
434
+
435
+ private
436
+ def from_hash(hash)
437
+ # TODO:
438
+ # - Clean this up. Doesn't look very nice
439
+ # - Raise errors if attribute/association is not present
440
+ hash.each do |k,v|
441
+ k = k.to_sym rescue k
442
+ if v.is_a?(Array) # This means this is a has_many association
443
+ unless (assoc = @associations[k]).nil?
444
+ name, child_klass = assoc.name, assoc.klass
445
+ v.each do |child|
446
+ child.is_a?(Hash) ? child_obj = child_klass.new(child) : child_obj = child
447
+ self.send "add_#{Inflector.singularize(name)}", child_obj
448
+ end
449
+ end
450
+ elsif v.is_a?(Hash) # This means this is a has_one association (which we might add later)
451
+ # Do nothing for now. More later
452
+ else # This means this is a normal attribute
453
+ self.send("#{k}=", v) if respond_to?("#{k}=") # @attributes.has_key?(k) || @attributes.has_key?("_#{k}")
454
+ end
455
+ end
456
+ end
457
+ end # End class Base
458
+ end # End module ActiveCouch