davber_couch_potato 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (80) hide show
  1. data/CHANGES.md +106 -0
  2. data/MIT-LICENSE.txt +19 -0
  3. data/README.md +409 -0
  4. data/VERSION.yml +5 -0
  5. data/init.rb +3 -0
  6. data/lib/core_ext/date.rb +21 -0
  7. data/lib/core_ext/object.rb +5 -0
  8. data/lib/core_ext/string.rb +8 -0
  9. data/lib/core_ext/symbol.rb +15 -0
  10. data/lib/core_ext/time.rb +21 -0
  11. data/lib/couch_potato/database.rb +161 -0
  12. data/lib/couch_potato/persistence/active_model_compliance.rb +44 -0
  13. data/lib/couch_potato/persistence/attachments.rb +31 -0
  14. data/lib/couch_potato/persistence/callbacks.rb +62 -0
  15. data/lib/couch_potato/persistence/dirty_attributes.rb +56 -0
  16. data/lib/couch_potato/persistence/ghost_attributes.rb +22 -0
  17. data/lib/couch_potato/persistence/json.rb +46 -0
  18. data/lib/couch_potato/persistence/magic_timestamps.rb +20 -0
  19. data/lib/couch_potato/persistence/properties.rb +86 -0
  20. data/lib/couch_potato/persistence/simple_property.rb +72 -0
  21. data/lib/couch_potato/persistence/type_caster.rb +40 -0
  22. data/lib/couch_potato/persistence.rb +105 -0
  23. data/lib/couch_potato/railtie.rb +18 -0
  24. data/lib/couch_potato/rspec/matchers/json2.js +482 -0
  25. data/lib/couch_potato/rspec/matchers/list_as_matcher.rb +54 -0
  26. data/lib/couch_potato/rspec/matchers/map_to_matcher.rb +49 -0
  27. data/lib/couch_potato/rspec/matchers/print_r.js +60 -0
  28. data/lib/couch_potato/rspec/matchers/reduce_to_matcher.rb +50 -0
  29. data/lib/couch_potato/rspec/matchers.rb +39 -0
  30. data/lib/couch_potato/rspec/stub_db.rb +46 -0
  31. data/lib/couch_potato/rspec.rb +2 -0
  32. data/lib/couch_potato/validation/with_active_model.rb +27 -0
  33. data/lib/couch_potato/validation/with_validatable.rb +37 -0
  34. data/lib/couch_potato/validation.rb +16 -0
  35. data/lib/couch_potato/view/base_view_spec.rb +67 -0
  36. data/lib/couch_potato/view/custom_view_spec.rb +42 -0
  37. data/lib/couch_potato/view/custom_views.rb +52 -0
  38. data/lib/couch_potato/view/lists.rb +23 -0
  39. data/lib/couch_potato/view/model_view_spec.rb +75 -0
  40. data/lib/couch_potato/view/properties_view_spec.rb +47 -0
  41. data/lib/couch_potato/view/raw_view_spec.rb +25 -0
  42. data/lib/couch_potato/view/view_query.rb +78 -0
  43. data/lib/couch_potato.rb +79 -0
  44. data/rails/init.rb +4 -0
  45. data/rails/reload_classes.rb +47 -0
  46. data/spec/attachments_spec.rb +23 -0
  47. data/spec/callbacks_spec.rb +308 -0
  48. data/spec/create_spec.rb +34 -0
  49. data/spec/custom_view_spec.rb +239 -0
  50. data/spec/default_property_spec.rb +38 -0
  51. data/spec/destroy_spec.rb +29 -0
  52. data/spec/fixtures/address.rb +10 -0
  53. data/spec/fixtures/person.rb +6 -0
  54. data/spec/property_spec.rb +315 -0
  55. data/spec/rails_spec.rb +51 -0
  56. data/spec/spec.opts +4 -0
  57. data/spec/spec_helper.rb +47 -0
  58. data/spec/unit/active_model_compliance_spec.rb +98 -0
  59. data/spec/unit/attributes_spec.rb +125 -0
  60. data/spec/unit/base_view_spec_spec.rb +73 -0
  61. data/spec/unit/callbacks_spec.rb +72 -0
  62. data/spec/unit/couch_potato_spec.rb +39 -0
  63. data/spec/unit/create_spec.rb +58 -0
  64. data/spec/unit/custom_views_spec.rb +15 -0
  65. data/spec/unit/database_spec.rb +266 -0
  66. data/spec/unit/date_spec.rb +22 -0
  67. data/spec/unit/dirty_attributes_spec.rb +166 -0
  68. data/spec/unit/json_create_id_spec.rb +14 -0
  69. data/spec/unit/lists_spec.rb +20 -0
  70. data/spec/unit/model_view_spec_spec.rb +13 -0
  71. data/spec/unit/properties_view_spec_spec.rb +31 -0
  72. data/spec/unit/rspec_matchers_spec.rb +124 -0
  73. data/spec/unit/rspec_stub_db_spec.rb +35 -0
  74. data/spec/unit/string_spec.rb +7 -0
  75. data/spec/unit/time_spec.rb +22 -0
  76. data/spec/unit/validation_spec.rb +67 -0
  77. data/spec/unit/view_query_spec.rb +78 -0
  78. data/spec/update_spec.rb +40 -0
  79. data/spec/view_updates_spec.rb +28 -0
  80. metadata +205 -0
data/CHANGES.md ADDED
@@ -0,0 +1,106 @@
1
+ ## Changes
2
+
3
+ ### 0.3.0 - cloned gem
4
+ * type field of documents now configurable, by using CouchPotato.type_field (davber)
5
+
6
+ ### 0.3.0
7
+ * support for lists (langalex)
8
+
9
+ ### 0.2.32
10
+ * added persisted? and to_key for proper ActiveModel compliance (thilo)
11
+ * id setter (jhohertz-work)
12
+ * load document ids if include\_documents is false (jweiss)
13
+ * persist given created\_at/updated\_at instead of Time.now (langalex)
14
+
15
+ ### 0.2.31
16
+ * Removed requirement for validatable gem. Allows for using more uptodate versions of the library, or doesn't install it when you're using ActiveModel. (mattmatt)
17
+ * fixed callbacks of super classes were not run (langalex)
18
+
19
+ ### 0.2.30
20
+ * pass in multiple keys when querying a view (langalex)
21
+
22
+ ### 0.2.29
23
+ * nicer inspect() for models (mattmatt)
24
+ * fixed (re)reduce for property views wasn't working (langalex)
25
+
26
+ ### 0.2.28
27
+ * fixed reloading nested classes (langalex)
28
+ * fixed constant missing error when loading models with uninitialized classes via views (langalex)
29
+ * added rspec helpers for stubbing out views (langalex)
30
+ * fixed design document names for nested model classes (svenfuchs)
31
+
32
+ ### 0.2.27
33
+ * workaround for Rails apps using bundler: database name was not initialized from couchdb.yml (langalex)
34
+
35
+ ### 0.2.26
36
+ * added to_s(:json) to Date and Time to be able to get properly formatted dates/times for searching with dates/times (langalex)
37
+ * all times are now stored as UTC (langalex)
38
+ * added support for Float attributes (arbovm)
39
+
40
+
41
+ ### 0.2.25
42
+ * automatic view updates: when you change the definition of a view couch potato will now update the design document in the database (langalex)
43
+ * support for properties of type Date, better support for Time (langalex)
44
+ * support for default reduce count methods in custom views (jweiss)
45
+
46
+ ### 0.2.24
47
+ * persistent instances can now be marked as dirty with #is_dirty (langalex)
48
+
49
+ ### 0.2.23
50
+ * Couch Potato models now conform to the ActiveModel interface when ActiveModel is installed, see http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ (langalex)
51
+ * fixed error with dirty tracking and BigDecimals (thilo)
52
+ * added the ability to use ActiveModel validations instead of validatable (martinrehfeld)
53
+
54
+ ### 0.2.22
55
+ * fixed properties with default values returned default when a blank value like '' or [] was set (langalex)
56
+
57
+ ### 0.2.21
58
+ * automatically set a database instance on results of CouchPotato::Database#view (langalex)
59
+ * improved auto loading of unloaded constants - can now load constants that have never been loaded before (langalex)
60
+ * raise exception on invalid parameters passed to a couchdb view query (langalex)
61
+ * when querying a view: pass in ranges as key instead of startkey/endkey, pass in plain value instead of hash with key (langalex)
62
+
63
+ ### 0.2.20
64
+ * support for :boolean properties (jweiss)
65
+ * return the total_rows when querying a view (langalex)
66
+
67
+ ### 0.2.19
68
+ * added conditions to views (langalex)
69
+
70
+ ### 0.2.18
71
+ * set Fixnum property to nil when given a blank string (langalex)
72
+
73
+ ### 0.2.17
74
+ * fixed nil attributes were omitted in json (jweiss, mattmatt)
75
+ * support for properties of type Fixnum (langalex)
76
+
77
+ ### 0.2.16
78
+ * fixed problem with classes being not loaded in rails development mode (langalex)
79
+ * fixed persist boolean false value (bernd)
80
+
81
+ ### 0.2.15
82
+ * ability to change the name of the attribute that stores the ruby class in the documents by setting JSON.create_id (lennart)
83
+ * fixed double loading issue with bundler (jweiss)
84
+ * fixed an issue with setting attachments (endor)
85
+
86
+ ### 0.2.13
87
+
88
+ * support adding errors in before_validation callbacks (mattmatt)
89
+ * support for inheritance (mattmatt)
90
+ * support for save without validations (mattmatt)
91
+ * improved (de)serialization now supports deserializing nested objects (railsbros, specs by hagenburger)
92
+ * RSpec matchers for testing map/reduce functions (langalex)
93
+
94
+ ### 0.2.10
95
+ * fixed bug with hardcoded timezone
96
+
97
+ ### 0.2.9
98
+
99
+ * allow to overwrite attribute accessor of properties and use super to call the original accessors
100
+ * allow read access to attributes that are present in the Couchdb document but not defined as properties
101
+ * support default values for properties via the :default parameter
102
+ * support attachments via the _attachments property
103
+ * support for namespaces models
104
+ * removed belongs_to macro for now
105
+ * removed CouchPotato::Config.database_server, just set CouchPotato::Config.database_name to the full url if you are not using localhost:5984
106
+ * Ruby 1.9 was broken and is now working again
data/MIT-LICENSE.txt ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2007 Bryan Helmkamp, Seth Fitzsimmons
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,409 @@
1
+ ## Couch Potato
2
+
3
+ ... is a persistence layer written in ruby for CouchDB.
4
+
5
+ This gem, *davber_couch_potato*, is a clone of the *couch_potato*, adding the capability to set the names of the design document and the *type* field, which is hard-coded to "ruby-class" in the original gem. This to enable interaction between other systems than the Couch Potato app with the CouchDB database. Hard-coded names are evil. Always.
6
+
7
+ This variant of the gem is created by David Bergman.
8
+
9
+ ### Mission
10
+
11
+ The goal of Couch Potato is to create a minimal framework in order to store and retrieve Ruby objects to/from CouchDB and create and query views.
12
+
13
+ It follows the document/view/querying semantics established by CouchDB and won't try to mimic ActiveRecord behavior in any way as that IS BAD.
14
+
15
+ Code that uses Couch Potato should be easy to test.
16
+
17
+ Lastly Couch Potato aims to provide a seamless integration with Ruby on Rails, e.g. routing, form helpers etc.
18
+
19
+ ### Core Features
20
+
21
+ * persisting objects by including the CouchPotato::Persistence module
22
+ * declarative views with either custom or generated map/reduce functions
23
+ * extensive spec suite
24
+
25
+ ### Installation
26
+
27
+ Couch Potato is hosted as a gem which you can install like this:
28
+
29
+ (sudo) gem install davber_couch_potato
30
+
31
+ #### Using with your ruby application:
32
+
33
+ require 'rubygems'
34
+ require 'couch_potato'
35
+
36
+ After that you configure the name of the database:
37
+
38
+ CouchPotato::Config.database_name = 'name_of_the_db'
39
+
40
+ The server URL will default to http://localhost:5984/ unless specified:
41
+
42
+ CouchPotato::Config.database_name = "http://example.com:5984/name_of_the_db"
43
+
44
+ Or with authentication
45
+
46
+ CouchPotato::Config.database_name = "http://username:password@example.com:5984/name_of_the_db"
47
+
48
+ Optionally you can configure which framework you want to use for validations (either validatable or ActiveModel)
49
+
50
+ CouchPotato::Config.validation_framework = :validatable | :active_model
51
+
52
+ #### Using with Rails
53
+
54
+ Add to your config/environment.rb:
55
+
56
+ config.gem 'davber_couch_potato', :source => 'http://gemcutter.org'
57
+ config.frameworks -= [:active_record] # if you switch completely
58
+
59
+ Then create a config/couchdb.yml:
60
+
61
+ development: development_db_name
62
+ test: test_db_name
63
+ production: http://db.server/production_db_name
64
+
65
+ Alternatively you can also install Couch Potato directly as a plugin.
66
+
67
+ ### Introduction
68
+
69
+ This is a basic tutorial on how to use Couch Potato. If you want to know all the details feel free to read the specs and the [rdocs](http://rdoc.info/projects/langalex/couch_potato).
70
+
71
+ #### Save, load objects
72
+
73
+ First you need a class.
74
+
75
+ class User
76
+ end
77
+
78
+ To make instances of this class persistent include the persistence module:
79
+
80
+ class User
81
+ include CouchPotato::Persistence
82
+ end
83
+
84
+ If you want to store any properties you have to declare them:
85
+
86
+ class User
87
+ include CouchPotato::Persistence
88
+
89
+ property :name
90
+ end
91
+
92
+ Properties can be typed:
93
+
94
+ class User
95
+ include CouchPotato::Persistence
96
+
97
+ property :address, :type => Address
98
+ end
99
+
100
+ In this case Address also implements CouchPotato::Persistence which means its JSON representation will be added to the user document.
101
+ Couch Potato also has support for the basic types (right now Fixnum, Date, Time and :boolean are supported):
102
+
103
+ class User
104
+ include CouchPotato::Persistence
105
+
106
+ property :age, :type => Fixnum
107
+ property :receive_newsletter, :type => :boolean
108
+ end
109
+
110
+ With this in place when you set the user's age as a String (e.g. using an hTML form) it will be converted into a Fixnum automatically.
111
+
112
+
113
+ Properties can have a default value:
114
+
115
+ class User
116
+ include CouchPotato::Persistence
117
+
118
+ property :active, :default => true
119
+ end
120
+
121
+ Now you can save your objects. All database operations are encapsulated in the CouchPotato::Database class. This separates your domain logic from the database access logic which makes it easier to write tests and also keeps you models smaller and cleaner.
122
+
123
+ user = User.new :name => 'joe'
124
+ CouchPotato.database.save_document user # or save_document!
125
+
126
+ You can of course also retrieve your instance:
127
+
128
+ CouchPotato.database.load_document "id_of_the_user_document" # => <#User 0x3075>
129
+
130
+
131
+ #### Properties
132
+
133
+ You can access the properties you declared above through normal attribute accessors.
134
+
135
+ user.name # => 'joe'
136
+ user.name = {:first => ['joe', 'joey'], :last => 'doe', :middle => 'J'} # you can set any ruby object that responds_to :to_json (includes all core objects)
137
+ user._id # => "02097f33a0046123f1ebc0ebb6937269"
138
+ user._rev # => "2769180384"
139
+ user.created_at # => Fri Oct 24 19:05:54 +0200 2008
140
+ user.updated_at # => Fri Oct 24 19:05:54 +0200 2008
141
+ user.new? # => false
142
+
143
+ If you want to have properties that don't map to any JSON type, i.e. other than String, Number, Boolean, Hash or Array you have to define the type like this:
144
+
145
+ class User
146
+ property :date_of_birth, :type => Date
147
+ end
148
+
149
+ The date_of_birth property is now automatically serialized to JSON and back when storing/retrieving objects.
150
+
151
+ #### Dirty tracking
152
+
153
+ CouchPotato tracks the dirty state of attributes in the same way ActiveRecord does:
154
+
155
+ user = User.create :name => 'joe'
156
+ user.name # => 'joe'
157
+ user.name_changed? # => false
158
+ user.name_was # => nil
159
+
160
+ You can also force a dirty state:
161
+
162
+ user.name = 'jane'
163
+ user.name_changed? # => true
164
+ user.name_not_changed
165
+ user.name_changed? # => false
166
+ CouchPotato.database.save_document user # does nothing as no attributes are dirty
167
+
168
+
169
+ #### Object validations
170
+
171
+ Couch Potato uses the validatable library for validation (http://validatable.rubyforge.org/)\
172
+
173
+ class User
174
+ property :name
175
+ validates_presence_of :name
176
+ end
177
+
178
+ user = User.new
179
+ user.valid? # => false
180
+ user.errors.on(:name) # => [:name, 'can't be blank']
181
+
182
+ #### Finding stuff / views / lists
183
+
184
+ In order to find data in your CouchDB you have to create a [view](http://books.couchdb.org/relax/design-documents/views) first. Couch Potato offers you to create and manage those views for you. All you have to do is declare them in your classes:
185
+
186
+ class User
187
+ include CouchPotato::Persistence
188
+ property :name
189
+
190
+ view :all, :key => :created_at
191
+ end
192
+
193
+ This will create a view called "all" in the "user" design document with a map function that emits "created_at" for every user document.
194
+
195
+ CouchPotato.database.view User.all
196
+
197
+ This will load all user documents in your database sorted by created_at.
198
+
199
+ CouchPotato.database.view User.all(:key => (Time.now- 10)..(Time.now), :descending => true)
200
+
201
+ Any options you pass in will be passed onto CouchDB.
202
+
203
+ Composite keys are also possible:
204
+
205
+ class User
206
+ property :name
207
+
208
+ view :all, :key => [:created_at, :name]
209
+ end
210
+
211
+ You can also pass conditions as a JavaScript string:
212
+
213
+ class User
214
+ property :name
215
+
216
+ view :completed, :key => :name, :conditions => 'doc.completed === true'
217
+ end
218
+
219
+ The creation of views is based on view specification classes (see [CouchPotato::View::BaseViewSpec](http://rdoc.info/rdoc/langalex/couch_potato/blob/e8f0069e5529ad08a1bd1f02637ea8f1d6d0ab5b/CouchPotato/View/BaseViewSpec.html) and its descendants for more detailed documentation). The above code uses the ModelViewSpec class which is used to find models by their properties. For more sophisticated searches you can use other view specifications (either use the built-in or provide your own) by passing a type parameter:
220
+
221
+ If you have larger structures and you only want to load some attributes you can use the PropertiesViewSpec (the full class name is automatically derived):
222
+
223
+ class User
224
+ property :name
225
+ property :bio
226
+
227
+ view :all, :key => :created_at, :properties => [:name], :type => :properties
228
+ end
229
+
230
+ CouchPotato.database.view(User.everyone).first.name # => "joe"
231
+ CouchPotato.database.view(User.everyone).first.bio # => nil
232
+
233
+ You can also pass in custom map/reduce functions with the custom view spec:
234
+
235
+ class User
236
+ view :all, :map => "function(doc) { emit(doc.created_at, null)}", :include_docs => true, :type => :custom
237
+ end
238
+
239
+ If you don't want the results to be converted into models the raw view is your friend:
240
+
241
+ class User
242
+ view :all, :map => "function(doc) { emit(doc.created_at, doc.name)}", :type => :raw
243
+ end
244
+
245
+ When querying this view you will get the raw data returned by CouchDB which looks something like this: {'total_entries': 2, 'rows': [{'value': 'alex', 'key': '2009-01-03 00:02:34 +000', 'id': '75976rgi7546gi02a'}]}
246
+
247
+ To process this raw data you can also pass in a results filter:
248
+
249
+ class User
250
+ view :all, :map => "function(doc) { emit(doc.created_at, doc.name)}", :type => :raw, :results_filter => lambda {|results| results['rows'].map{|row| row['value']}}
251
+ end
252
+
253
+ In this case querying the view would only return the emitted value for each row.
254
+
255
+ You can pass in your own view specifications by passing in :type => MyViewSpecClass. Take a look at the CouchPotato::View::*ViewSpec classes to get an idea of how this works.
256
+
257
+ ##### Lists
258
+
259
+ CouchPotato also supports [CouchDB lists](http://books.couchdb.org/relax/design-documents/lists). With lists you can process the result of a view query with another JavaScript function. This can be useful for example if you want to filter your results, or add some data to each document.
260
+
261
+ Defining a list works similarly to views:
262
+
263
+ class User
264
+ include CouchPotato::Persistence
265
+
266
+ property :first_name
267
+ view :with_full_name, key: first_namne, list: :add_last_name
268
+ view :all, key: :first_name
269
+
270
+ list :add_last_name, <<-JS
271
+ function(head, req) {
272
+ var row;
273
+ send('{"rows": [');
274
+ while(row = getRow()) {
275
+ row.doc.name = row.doc.first_name + ' doe';
276
+ send(JSON.stringify(row));
277
+ };
278
+ send(']}');
279
+ }
280
+ JS
281
+ end
282
+
283
+ CouchPotato.database.save User.new(first_name: 'joe')
284
+ CouchPotato.database.view(User.with_full_name).first.name # => 'joe doe'
285
+
286
+ You can also pass in the list at query time:
287
+
288
+ CouchPotato.database.view(User.all(list: :add_last_name))
289
+
290
+ #### Associations
291
+
292
+ Not supported. Not sure if they ever will be. You can implement those yourself using views and custom methods on your models.
293
+
294
+ #### Callbacks
295
+
296
+ Couch Potato supports the usual lifecycle callbacks known from ActiveRecord:
297
+
298
+ class User
299
+ include CouchPotato::Persistence
300
+
301
+ before_create :do_something_before_create
302
+ before_update {|user| user.do_something_on_update}
303
+ end
304
+
305
+ This will call the method do_something_before_create before creating an object and run the given lambda before updating one. Lambda callbacks get passed the model as their first argument. Method callbacks don't receive any arguments.
306
+
307
+ Supported callbacks are: :before_validation, :before_validation_on_create, :before_validation_on_update, :before_validation_on_save, :before_create, :after_create, :before_update, :after_update, :before_save, :after_save, :before_destroy, :after_destroy.
308
+
309
+ If you need access to the database in a callback: Couch Potato automatically assigns a database instance to the model before saving and when loading. It is available as _database_ accessor from within your model instance.
310
+
311
+ #### Attachments
312
+
313
+ There is basic attachment support: if you want to store any attachments set the _attachments attribute of a model before saving like this:
314
+
315
+ class User
316
+ include CouchPotato::Persistence
317
+ end
318
+
319
+ data = File.read('some_file.text') # or from upload
320
+ user = User.new
321
+ user._attachments = {'photo' => {'data' => data, 'content_type' => 'image/png'}}
322
+
323
+ When saving this object an attachment with the name _photo_ will be uploaded into CouchDB. It will be available under the url of the user object + _/photo_. When loading the user at a later time you still have access to the _content_type_ and additionally to the _length_ of the attachment:
324
+
325
+ user_reloaded = CouchPotato.database.load user.id
326
+ user_reloaded._attachments['photo'] # => {'content_type' => 'image/png', 'length' => 37861}
327
+
328
+ #### Testing
329
+
330
+ To make testing easier and faster database logic has been put into its own class, which you can replace and stub out in whatever way you want:
331
+
332
+ class User
333
+ include CouchPotato::Persistence
334
+ end
335
+
336
+ # RSpec
337
+ describe 'save a user' do
338
+ it 'should save' do
339
+ couchrest_db = stub 'couchrest_db',
340
+ database = CouchPotato::Database.new couchrest_db
341
+ user = User.new
342
+ couchrest_db.should_receive(:save_doc).with(...)
343
+ database.save_document user
344
+ end
345
+ end
346
+
347
+ By creating you own instances of CouchPotato::Database and passing them a fake CouchRest database instance you can completely disconnect your unit tests/spec from the database.
348
+
349
+ For stubbing out the database couch potato offers some helpers:
350
+
351
+ class Comment
352
+ view :by_commenter_id, :key => :commenter_id
353
+ end
354
+
355
+ # RSpec
356
+ require 'couch_potato/rspec'
357
+
358
+ db = stub_db # stubs CouchPotato.database
359
+ db.stub_view(Comment, :by_commenter_id).with('23').and_return([:comment1, :comment2])
360
+
361
+ CouchPotato.database.view(Comment.by_commenter_id('23)) # => [:comment1, :comment2]
362
+
363
+ ##### Testing map/reduce functions
364
+
365
+ Couch Potato provides custom RSpec matchers for testing the map and reduce functions of your views. For example you can do this:
366
+
367
+ Class User
368
+ include CouchPotato::Persistence
369
+
370
+ view :by_name, :key => :name
371
+ view :by_age, :key => :age
372
+ end
373
+
374
+ #RSpec
375
+ require 'couch_potato/rspec'
376
+
377
+ describe User, 'by_name' do
378
+ it "should map users to their name" do
379
+ User.by_name.should map(User.new(:name => 'bill', :age => 23)).to(['bill', null])
380
+ end
381
+
382
+ it "should reduce the users to the sum of their age" do
383
+ User.by_age.should reduce([], [[23], [22]]).to(45)
384
+ end
385
+
386
+ it "should rereduce" do
387
+ User.by_age.should rereduce([], [[23], [22]]).to(45)
388
+ end
389
+ end
390
+
391
+ This will actually run your map/reduce functions in a JavaScript interpreter, passing the arguments as JSON and converting the results back to Ruby. For more examples see the [spec](http://github.com/langalex/couch_potato/blob/master/spec/unit/rspec_matchers_spec.rb).
392
+
393
+ In order for this to work you must have the `js` executable in your PATH. This is usually part of the _spidermonkey_ package/port. (On MacPorts that's _spidemonkey_, on Linux it could be one of _libjs_, _libmozjs_ or _libspidermonkey_). When you installed CouchDB via your packet manager Spidermonkey should already be there.
394
+
395
+ ### Helping out
396
+
397
+ Please fix bugs, add more specs, implement new features by forking the github repo at http://github.com/langalex/couch_potato.
398
+
399
+ Issues are tracked at github: http://github.com/langalex/couch_potato/issues
400
+
401
+ There is a mailing list, just write to: couchpotato@librelist.com
402
+
403
+ You can run all the specs by calling 'rake spec_unit' and 'rake spec_functional' in the root folder of Couch Potato. The specs require a running CouchDB instance at http://localhost:5984
404
+
405
+ I will only accept patches that are covered by specs - sorry.
406
+
407
+ ### Contact
408
+
409
+ If you have any questions/suggestions etc. please contact me at alex at upstream-berlin.com or @langalex on twitter.
data/VERSION.yml ADDED
@@ -0,0 +1,5 @@
1
+ ---
2
+ :major: 0
3
+ :minor: 3
4
+ :patch: 0
5
+ :build:
data/init.rb ADDED
@@ -0,0 +1,3 @@
1
+ # this is for rails only
2
+
3
+ require File.dirname(__FILE__) + '/rails/init'
@@ -0,0 +1,21 @@
1
+ class Date
2
+ def to_json(*a)
3
+ %("#{to_s(:json)}")
4
+ end
5
+
6
+ def to_s_with_json(*args)
7
+ if args[0] == :json
8
+ strftime("%Y/%m/%d")
9
+ else
10
+ to_s_without_json *args
11
+ end
12
+ end
13
+ alias_method :to_s_without_json, :to_s
14
+ alias_method :to_s, :to_s_with_json
15
+
16
+
17
+ def self.json_create string
18
+ return nil if string.nil?
19
+ Date.parse(string)
20
+ end
21
+ end
@@ -0,0 +1,5 @@
1
+ Object.class_eval do
2
+ def try(method, *args)
3
+ self.send method, *args if self.respond_to?(method)
4
+ end
5
+ end
@@ -0,0 +1,8 @@
1
+ module ActiveSupportMethods
2
+ def camelize
3
+ sub(/^([a-z])/) {$1.upcase}.gsub(/_([a-z])/) do
4
+ $1.upcase
5
+ end
6
+ end
7
+ end
8
+ String.send :include, ActiveSupportMethods unless String.new.respond_to?(:underscore)
@@ -0,0 +1,15 @@
1
+ # taken from ActiveSupport 2.3.2
2
+ unless :to_proc.respond_to?(:to_proc)
3
+ class Symbol
4
+ # Turns the symbol into a simple proc, which is especially useful for enumerations. Examples:
5
+ #
6
+ # # The same as people.collect { |p| p.name }
7
+ # people.collect(&:name)
8
+ #
9
+ # # The same as people.select { |p| p.manager? }.collect { |p| p.salary }
10
+ # people.select(&:manager?).collect(&:salary)
11
+ def to_proc
12
+ Proc.new { |*args| args.shift.__send__(self, *args) }
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,21 @@
1
+ class Time
2
+ def to_json(*a)
3
+ %("#{to_s(:json)}")
4
+ end
5
+
6
+ def to_s_with_json(*args)
7
+ if args[0] == :json
8
+ getutc.strftime("%Y/%m/%d %H:%M:%S +0000")
9
+ else
10
+ to_s_without_json *args
11
+ end
12
+ end
13
+ alias_method :to_s_without_json, :to_s
14
+ alias_method :to_s, :to_s_with_json
15
+
16
+ def self.json_create string
17
+ return nil if string.nil?
18
+ d = DateTime.parse(string).new_offset
19
+ self.utc(d.year, d.month, d.day, d.hour, d.min, d.sec)
20
+ end
21
+ end