oz-couchrest 0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. data/LICENSE +176 -0
  2. data/README.md +95 -0
  3. data/Rakefile +74 -0
  4. data/THANKS.md +18 -0
  5. data/examples/model/example.rb +144 -0
  6. data/examples/word_count/markov +38 -0
  7. data/examples/word_count/views/books/chunked-map.js +3 -0
  8. data/examples/word_count/views/books/united-map.js +1 -0
  9. data/examples/word_count/views/markov/chain-map.js +6 -0
  10. data/examples/word_count/views/markov/chain-reduce.js +7 -0
  11. data/examples/word_count/views/word_count/count-map.js +6 -0
  12. data/examples/word_count/views/word_count/count-reduce.js +3 -0
  13. data/examples/word_count/word_count.rb +46 -0
  14. data/examples/word_count/word_count_query.rb +40 -0
  15. data/examples/word_count/word_count_views.rb +26 -0
  16. data/lib/couchrest.rb +198 -0
  17. data/lib/couchrest/commands/generate.rb +71 -0
  18. data/lib/couchrest/commands/push.rb +103 -0
  19. data/lib/couchrest/core/database.rb +326 -0
  20. data/lib/couchrest/core/design.rb +91 -0
  21. data/lib/couchrest/core/document.rb +87 -0
  22. data/lib/couchrest/core/response.rb +16 -0
  23. data/lib/couchrest/core/server.rb +88 -0
  24. data/lib/couchrest/core/view.rb +4 -0
  25. data/lib/couchrest/helper/pager.rb +103 -0
  26. data/lib/couchrest/helper/streamer.rb +44 -0
  27. data/lib/couchrest/helper/upgrade.rb +51 -0
  28. data/lib/couchrest/mixins.rb +4 -0
  29. data/lib/couchrest/mixins/attachments.rb +31 -0
  30. data/lib/couchrest/mixins/callbacks.rb +483 -0
  31. data/lib/couchrest/mixins/class_proxy.rb +112 -0
  32. data/lib/couchrest/mixins/collection.rb +222 -0
  33. data/lib/couchrest/mixins/design_doc.rb +114 -0
  34. data/lib/couchrest/mixins/document_queries.rb +53 -0
  35. data/lib/couchrest/mixins/extended_attachments.rb +74 -0
  36. data/lib/couchrest/mixins/extended_document_mixins.rb +8 -0
  37. data/lib/couchrest/mixins/properties.rb +125 -0
  38. data/lib/couchrest/mixins/validation.rb +257 -0
  39. data/lib/couchrest/mixins/views.rb +211 -0
  40. data/lib/couchrest/monkeypatches.rb +112 -0
  41. data/lib/couchrest/more/casted_model.rb +29 -0
  42. data/lib/couchrest/more/extended_document.rb +232 -0
  43. data/lib/couchrest/more/property.rb +40 -0
  44. data/lib/couchrest/support/blank.rb +42 -0
  45. data/lib/couchrest/support/class.rb +176 -0
  46. data/lib/couchrest/support/rails.rb +35 -0
  47. data/lib/couchrest/validation/auto_validate.rb +161 -0
  48. data/lib/couchrest/validation/contextual_validators.rb +78 -0
  49. data/lib/couchrest/validation/validation_errors.rb +118 -0
  50. data/lib/couchrest/validation/validators/absent_field_validator.rb +74 -0
  51. data/lib/couchrest/validation/validators/confirmation_validator.rb +99 -0
  52. data/lib/couchrest/validation/validators/format_validator.rb +117 -0
  53. data/lib/couchrest/validation/validators/formats/email.rb +66 -0
  54. data/lib/couchrest/validation/validators/formats/url.rb +43 -0
  55. data/lib/couchrest/validation/validators/generic_validator.rb +120 -0
  56. data/lib/couchrest/validation/validators/length_validator.rb +134 -0
  57. data/lib/couchrest/validation/validators/method_validator.rb +89 -0
  58. data/lib/couchrest/validation/validators/numeric_validator.rb +104 -0
  59. data/lib/couchrest/validation/validators/required_field_validator.rb +109 -0
  60. data/spec/couchrest/core/couchrest_spec.rb +201 -0
  61. data/spec/couchrest/core/database_spec.rb +700 -0
  62. data/spec/couchrest/core/design_spec.rb +138 -0
  63. data/spec/couchrest/core/document_spec.rb +267 -0
  64. data/spec/couchrest/core/server_spec.rb +35 -0
  65. data/spec/couchrest/helpers/pager_spec.rb +122 -0
  66. data/spec/couchrest/helpers/streamer_spec.rb +23 -0
  67. data/spec/couchrest/more/casted_extended_doc_spec.rb +75 -0
  68. data/spec/couchrest/more/casted_model_spec.rb +177 -0
  69. data/spec/couchrest/more/extended_doc_attachment_spec.rb +135 -0
  70. data/spec/couchrest/more/extended_doc_spec.rb +563 -0
  71. data/spec/couchrest/more/extended_doc_subclass_spec.rb +98 -0
  72. data/spec/couchrest/more/extended_doc_view_spec.rb +414 -0
  73. data/spec/couchrest/more/property_spec.rb +146 -0
  74. data/spec/fixtures/attachments/README +3 -0
  75. data/spec/fixtures/attachments/couchdb.png +0 -0
  76. data/spec/fixtures/attachments/test.html +11 -0
  77. data/spec/fixtures/more/article.rb +34 -0
  78. data/spec/fixtures/more/card.rb +22 -0
  79. data/spec/fixtures/more/cat.rb +18 -0
  80. data/spec/fixtures/more/course.rb +14 -0
  81. data/spec/fixtures/more/event.rb +6 -0
  82. data/spec/fixtures/more/invoice.rb +17 -0
  83. data/spec/fixtures/more/person.rb +8 -0
  84. data/spec/fixtures/more/question.rb +6 -0
  85. data/spec/fixtures/more/service.rb +12 -0
  86. data/spec/fixtures/views/lib.js +3 -0
  87. data/spec/fixtures/views/test_view/lib.js +3 -0
  88. data/spec/fixtures/views/test_view/only-map.js +4 -0
  89. data/spec/fixtures/views/test_view/test-map.js +3 -0
  90. data/spec/fixtures/views/test_view/test-reduce.js +3 -0
  91. data/spec/spec.opts +6 -0
  92. data/spec/spec_helper.rb +37 -0
  93. data/utils/remap.rb +27 -0
  94. data/utils/subset.rb +30 -0
  95. metadata +194 -0
@@ -0,0 +1,103 @@
1
+ module CouchRest
2
+
3
+ module Commands
4
+
5
+ module Push
6
+
7
+ def self.run(options)
8
+ directory = options[:directory]
9
+ database = options[:trailing_args].first
10
+
11
+ fm = CouchRest::FileManager.new(database)
12
+ fm.loud = options[:loud]
13
+
14
+ if options[:loud]
15
+ puts "Pushing views from directory #{directory} to database #{fm.db}"
16
+ end
17
+
18
+ fm.push_views(directory)
19
+ end
20
+
21
+ def self.help
22
+ helpstring = <<-GEN
23
+
24
+ == Pushing views with Couchview ==
25
+
26
+ Usage: couchview push directory dbname
27
+
28
+ Couchview expects a specific filesystem layout for your CouchDB views (see
29
+ example below). It also supports advanced features like inlining of library
30
+ code (so you can keep DRY) as well as avoiding unnecessary document
31
+ modification.
32
+
33
+ Couchview also solves a problem with CouchDB's view API, which only provides
34
+ access to the final reduce side of any views which have both a map and a
35
+ reduce function defined. The intermediate map results are often useful for
36
+ development and production. CouchDB is smart enough to reuse map indexes for
37
+ functions duplicated across views within the same design document.
38
+
39
+ For views with a reduce function defined, Couchview creates both a reduce view
40
+ and a map-only view, so that you can browse and query the map side as well as
41
+ the reduction, with no performance penalty.
42
+
43
+ == Example ==
44
+
45
+ couchview push foo-project/bar-views baz-database
46
+
47
+ This will push the views defined in foo-project/bar-views into a database
48
+ called baz-database. Couchview expects the views to be defined in files with
49
+ names like:
50
+
51
+ foo-project/bar-views/my-design/viewname-map.js
52
+ foo-project/bar-views/my-design/viewname-reduce.js
53
+ foo-project/bar-views/my-design/noreduce-map.js
54
+
55
+ Pushed to => http://127.0.0.1:5984/baz-database/_design/my-design
56
+
57
+ And the design document:
58
+ {
59
+ "views" : {
60
+ "viewname-map" : {
61
+ "map" : "### contents of view-name-map.js ###"
62
+ },
63
+ "viewname-reduce" : {
64
+ "map" : "### contents of view-name-map.js ###",
65
+ "reduce" : "### contents of view-name-reduce.js ###"
66
+ },
67
+ "noreduce-map" : {
68
+ "map" : "### contents of noreduce-map.js ###"
69
+ }
70
+ }
71
+ }
72
+
73
+ Couchview will create a design document for each subdirectory of the views
74
+ directory specified on the command line.
75
+
76
+ == Library Inlining ==
77
+
78
+ Couchview can optionally inline library code into your views so you only have
79
+ to maintain it in one place. It looks for any files named lib.* in your
80
+ design-doc directory (for doc specific libs) and in the parent views directory
81
+ (for project global libs). These libraries are only inserted into views which
82
+ include the text
83
+
84
+ // !include lib
85
+
86
+ or
87
+
88
+ # !include lib
89
+
90
+ Couchview is a result of scratching my own itch. I'd be happy to make it more
91
+ general, so please contact me at jchris@grabb.it if you'd like to see anything
92
+ added or changed.
93
+
94
+ GEN
95
+ helpstring.gsub(/^ /, '')
96
+ end
97
+
98
+ end
99
+
100
+
101
+ end
102
+
103
+ end
@@ -0,0 +1,326 @@
1
+ require 'cgi'
2
+ require "base64"
3
+
4
+ module CouchRest
5
+ class Database
6
+ attr_reader :server, :host, :name, :root, :uri
7
+ attr_accessor :bulk_save_cache_limit
8
+
9
+ # Create a CouchRest::Database adapter for the supplied CouchRest::Server
10
+ # and database name.
11
+ #
12
+ # ==== Parameters
13
+ # server<CouchRest::Server>:: database host
14
+ # name<String>:: database name
15
+ #
16
+ def initialize(server, name)
17
+ @name = name
18
+ @server = server
19
+ @host = server.uri
20
+ @uri = "/#{name.gsub('/','%2F')}"
21
+ @root = host + uri
22
+ @streamer = Streamer.new(self)
23
+ @bulk_save_cache = []
24
+ @bulk_save_cache_limit = 500 # must be smaller than the uuid count
25
+ end
26
+
27
+ # returns the database's uri
28
+ def to_s
29
+ @root
30
+ end
31
+
32
+ # GET the database info from CouchDB
33
+ def info
34
+ CouchRest.get @root
35
+ end
36
+
37
+ # Query the <tt>_all_docs</tt> view. Accepts all the same arguments as view.
38
+ def documents(params = {})
39
+ keys = params.delete(:keys)
40
+ url = CouchRest.paramify_url "#{@root}/_all_docs", params
41
+ if keys
42
+ CouchRest.post(url, {:keys => keys})
43
+ else
44
+ CouchRest.get url
45
+ end
46
+ end
47
+
48
+ # load a set of documents by passing an array of ids
49
+ def get_bulk(ids)
50
+ documents(:keys => ids, :include_docs => true)
51
+ end
52
+ alias :bulk_load :get_bulk
53
+
54
+ # POST a temporary view function to CouchDB for querying. This is not
55
+ # recommended, as you don't get any performance benefit from CouchDB's
56
+ # materialized views. Can be quite slow on large databases.
57
+ def slow_view(funcs, params = {})
58
+ keys = params.delete(:keys)
59
+ funcs = funcs.merge({:keys => keys}) if keys
60
+ url = CouchRest.paramify_url "#{@root}/_temp_view", params
61
+ JSON.parse(RestClient.post(url, funcs.to_json, {"Content-Type" => 'application/json'}))
62
+ end
63
+
64
+ # backwards compatibility is a plus
65
+ alias :temp_view :slow_view
66
+
67
+ # Query a CouchDB view as defined by a <tt>_design</tt> document. Accepts
68
+ # paramaters as described in http://wiki.apache.org/couchdb/HttpViewApi
69
+ def view(name, params = {}, &block)
70
+ keys = params.delete(:keys)
71
+ name = name.split('/') # I think this will always be length == 2, but maybe not...
72
+ dname = name.shift
73
+ vname = name.join('/')
74
+ url = CouchRest.paramify_url "#{@root}/_design/#{dname}/_view/#{vname}", params
75
+ if keys
76
+ CouchRest.post(url, {:keys => keys})
77
+ else
78
+ if block_given?
79
+ @streamer.view("_design/#{dname}/_view/#{vname}", params, &block)
80
+ else
81
+ CouchRest.get url
82
+ end
83
+ end
84
+ end
85
+
86
+ def search(name, params={})
87
+ url = CouchRest.paramify_url "#{root}/_fti/#{name}", params
88
+ # -> http://localhost:5984/artdb/_fti/Location/by_name?include_docs=true&q=p*'
89
+ CouchRest.get url
90
+ end
91
+
92
+ # GET a document from CouchDB, by id. Returns a Ruby Hash.
93
+ def get(id, params = {})
94
+ slug = escape_docid(id)
95
+ url = CouchRest.paramify_url("#{@root}/#{slug}", params)
96
+ result = CouchRest.get(url)
97
+ return result unless result.is_a?(Hash)
98
+ doc = if /^_design/ =~ result["_id"]
99
+ Design.new(result)
100
+ else
101
+ Document.new(result)
102
+ end
103
+ doc.database = self
104
+ doc
105
+ end
106
+
107
+ # GET an attachment directly from CouchDB
108
+ def fetch_attachment(doc, name)
109
+ # slug = escape_docid(docid)
110
+ # name = CGI.escape(name)
111
+ uri = url_for_attachment(doc, name)
112
+ RestClient.get uri
113
+ # "#{@uri}/#{slug}/#{name}"
114
+ end
115
+
116
+ # PUT an attachment directly to CouchDB
117
+ def put_attachment(doc, name, file, options = {})
118
+ docid = escape_docid(doc['_id'])
119
+ name = CGI.escape(name)
120
+ uri = url_for_attachment(doc, name)
121
+ JSON.parse(RestClient.put(uri, file, options))
122
+ end
123
+
124
+ # DELETE an attachment directly from CouchDB
125
+ def delete_attachment doc, name
126
+ uri = url_for_attachment(doc, name)
127
+ # this needs a rev
128
+ JSON.parse(RestClient.delete(uri))
129
+ end
130
+
131
+ # Save a document to CouchDB. This will use the <tt>_id</tt> field from
132
+ # the document as the id for PUT, or request a new UUID from CouchDB, if
133
+ # no <tt>_id</tt> is present on the document. IDs are attached to
134
+ # documents on the client side because POST has the curious property of
135
+ # being automatically retried by proxies in the event of network
136
+ # segmentation and lost responses.
137
+ #
138
+ # If <tt>bulk</tt> is true (false by default) the document is cached for bulk-saving later.
139
+ # Bulk saving happens automatically when #bulk_save_cache limit is exceded, or on the next non bulk save.
140
+ def save_doc(doc, bulk = false)
141
+ if doc['_attachments']
142
+ doc['_attachments'] = encode_attachments(doc['_attachments'])
143
+ end
144
+ if bulk
145
+ @bulk_save_cache << doc
146
+ return bulk_save if @bulk_save_cache.length >= @bulk_save_cache_limit
147
+ return {"ok" => true} # Compatibility with Document#save
148
+ elsif !bulk && @bulk_save_cache.length > 0
149
+ bulk_save
150
+ end
151
+ result = if doc['_id']
152
+ slug = escape_docid(doc['_id'])
153
+ begin
154
+ CouchRest.put "#{@root}/#{slug}", doc
155
+ rescue RestClient::ResourceNotFound
156
+ p "resource not found when saving even tho an id was passed"
157
+ slug = doc['_id'] = @server.next_uuid
158
+ CouchRest.put "#{@root}/#{slug}", doc
159
+ end
160
+ else
161
+ begin
162
+ slug = doc['_id'] = @server.next_uuid
163
+ CouchRest.put "#{@root}/#{slug}", doc
164
+ rescue #old version of couchdb
165
+ CouchRest.post @root, doc
166
+ end
167
+ end
168
+ if result['ok']
169
+ doc['_id'] = result['id']
170
+ doc['_rev'] = result['rev']
171
+ doc.database = self if doc.respond_to?(:database=)
172
+ end
173
+ result
174
+ end
175
+
176
+ ### DEPRECATION NOTICE
177
+ def save(doc, bulk=false)
178
+ puts "CouchRest::Database's save method is being deprecated, please use save_doc instead"
179
+ save_doc(doc, bulk)
180
+ end
181
+
182
+
183
+ # POST an array of documents to CouchDB. If any of the documents are
184
+ # missing ids, supply one from the uuid cache.
185
+ #
186
+ # If called with no arguments, bulk saves the cache of documents to be bulk saved.
187
+ def bulk_save(docs = nil, use_uuids = true)
188
+ if docs.nil?
189
+ docs = @bulk_save_cache
190
+ @bulk_save_cache = []
191
+ end
192
+ if (use_uuids)
193
+ ids, noids = docs.partition{|d|d['_id']}
194
+ uuid_count = [noids.length, @server.uuid_batch_count].max
195
+ noids.each do |doc|
196
+ nextid = @server.next_uuid(uuid_count) rescue nil
197
+ doc['_id'] = nextid if nextid
198
+ end
199
+ end
200
+ CouchRest.post "#{@root}/_bulk_docs", {:docs => docs}
201
+ end
202
+ alias :bulk_delete :bulk_save
203
+
204
+ # DELETE the document from CouchDB that has the given <tt>_id</tt> and
205
+ # <tt>_rev</tt>.
206
+ #
207
+ # If <tt>bulk</tt> is true (false by default) the deletion is recorded for bulk-saving (bulk-deletion :) later.
208
+ # Bulk saving happens automatically when #bulk_save_cache limit is exceded, or on the next non bulk save.
209
+ def delete_doc(doc, bulk = false)
210
+ raise ArgumentError, "_id and _rev required for deleting" unless doc['_id'] && doc['_rev']
211
+ if bulk
212
+ @bulk_save_cache << { '_id' => doc['_id'], '_rev' => doc['_rev'], '_deleted' => true }
213
+ return bulk_save if @bulk_save_cache.length >= @bulk_save_cache_limit
214
+ return { "ok" => true } # Mimic the non-deferred version
215
+ end
216
+ slug = escape_docid(doc['_id'])
217
+ CouchRest.delete "#{@root}/#{slug}?rev=#{doc['_rev']}"
218
+ end
219
+
220
+ ### DEPRECATION NOTICE
221
+ def delete(doc, bulk=false)
222
+ puts "CouchRest::Database's delete method is being deprecated, please use delete_doc instead"
223
+ delete_doc(doc, bulk)
224
+ end
225
+
226
+ # COPY an existing document to a new id. If the destination id currently exists, a rev must be provided.
227
+ # <tt>dest</tt> can take one of two forms if overwriting: "id_to_overwrite?rev=revision" or the actual doc
228
+ # hash with a '_rev' key
229
+ def copy_doc(doc, dest)
230
+ raise ArgumentError, "_id is required for copying" unless doc['_id']
231
+ slug = escape_docid(doc['_id'])
232
+ destination = if dest.respond_to?(:has_key?) && dest['_id'] && dest['_rev']
233
+ "#{dest['_id']}?rev=#{dest['_rev']}"
234
+ else
235
+ dest
236
+ end
237
+ CouchRest.copy "#{@root}/#{slug}", destination
238
+ end
239
+
240
+ ### DEPRECATION NOTICE
241
+ def copy(doc, dest)
242
+ puts "CouchRest::Database's copy method is being deprecated, please use copy_doc instead"
243
+ copy_doc(doc, dest)
244
+ end
245
+
246
+ # Compact the database, removing old document revisions and optimizing space use.
247
+ def compact!
248
+ CouchRest.post "#{@root}/_compact"
249
+ end
250
+
251
+ # Create the database
252
+ def create!
253
+ bool = server.create_db(@name) rescue false
254
+ bool && true
255
+ end
256
+
257
+ # Delete and re create the database
258
+ def recreate!
259
+ delete!
260
+ create!
261
+ rescue RestClient::ResourceNotFound
262
+ ensure
263
+ create!
264
+ end
265
+
266
+ # Replicates via "pulling" from another database to this database. Makes no attempt to deal with conflicts.
267
+ def replicate_from other_db
268
+ raise ArgumentError, "must provide a CouchReset::Database" unless other_db.kind_of?(CouchRest::Database)
269
+ CouchRest.post "#{@host}/_replicate", :source => other_db.root, :target => name
270
+ end
271
+
272
+ # Replicates via "pushing" to another database. Makes no attempt to deal with conflicts.
273
+ def replicate_to other_db
274
+ raise ArgumentError, "must provide a CouchReset::Database" unless other_db.kind_of?(CouchRest::Database)
275
+ CouchRest.post "#{@host}/_replicate", :target => other_db.root, :source => name
276
+ end
277
+
278
+ # DELETE the database itself. This is not undoable and could be rather
279
+ # catastrophic. Use with care!
280
+ def delete!
281
+ clear_extended_doc_fresh_cache
282
+ CouchRest.delete @root
283
+ end
284
+
285
+ private
286
+
287
+ def clear_extended_doc_fresh_cache
288
+ ::CouchRest::ExtendedDocument.subclasses.each{|klass| klass.design_doc_fresh = false if klass.respond_to?(:design_doc_fresh=) }
289
+ end
290
+
291
+ def uri_for_attachment(doc, name)
292
+ if doc.is_a?(String)
293
+ puts "CouchRest::Database#fetch_attachment will eventually require a doc as the first argument, not a doc.id"
294
+ docid = doc
295
+ rev = nil
296
+ else
297
+ docid = doc['_id']
298
+ rev = doc['_rev']
299
+ end
300
+ docid = escape_docid(docid)
301
+ name = CGI.escape(name)
302
+ rev = "?rev=#{doc['_rev']}" if rev
303
+ "/#{docid}/#{name}#{rev}"
304
+ end
305
+
306
+ def url_for_attachment(doc, name)
307
+ @root + uri_for_attachment(doc, name)
308
+ end
309
+
310
+ def escape_docid id
311
+ /^_design\/(.*)/ =~ id ? "_design/#{CGI.escape($1)}" : CGI.escape(id)
312
+ end
313
+
314
+ def encode_attachments(attachments)
315
+ attachments.each do |k,v|
316
+ next if v['stub']
317
+ v['data'] = base64(v['data'])
318
+ end
319
+ attachments
320
+ end
321
+
322
+ def base64(data)
323
+ Base64.encode64(data).gsub(/\s/,'')
324
+ end
325
+ end
326
+ end
@@ -0,0 +1,91 @@
1
+ module CouchRest
2
+ class Design < Document
3
+ def view_by *keys
4
+ opts = keys.pop if keys.last.is_a?(Hash)
5
+ opts ||= {}
6
+ self['views'] ||= {}
7
+ method_name = "by_#{keys.join('_and_')}"
8
+
9
+ if opts[:map]
10
+ view = {}
11
+ view['map'] = opts.delete(:map)
12
+ if opts[:reduce]
13
+ view['reduce'] = opts.delete(:reduce)
14
+ opts[:reduce] = false
15
+ end
16
+ self['views'][method_name] = view
17
+ else
18
+ doc_keys = keys.collect{|k|"doc['#{k}']"} # this is where :require => 'doc.x == true' would show up
19
+ key_emit = doc_keys.length == 1 ? "#{doc_keys.first}" : "[#{doc_keys.join(', ')}]"
20
+ guards = opts.delete(:guards) || []
21
+ guards.concat doc_keys
22
+ map_function = <<-JAVASCRIPT
23
+ function(doc) {
24
+ if (#{guards.join(' && ')}) {
25
+ emit(#{key_emit}, null);
26
+ }
27
+ }
28
+ JAVASCRIPT
29
+ self['views'][method_name] = {
30
+ 'map' => map_function
31
+ }
32
+ end
33
+ self['views'][method_name]['couchrest-defaults'] = opts unless opts.empty?
34
+ method_name
35
+ end
36
+
37
+ def search_by *keys
38
+ search_view_name = "by_#{keys.pop.to_s}"
39
+ raise StandardError, "No fulltext views found in design #{name}" unless self['fulltext']
40
+ return "search_#{search_view_name}" if self['fulltext'][search_view_name]
41
+ raise StandardError, "Missing search view in design #{self.id}"
42
+ end
43
+
44
+ # Dispatches to any named view.
45
+ # (using the database where this design doc was saved)
46
+ def view view_name, query={}, &block
47
+ view_on database, view_name, query, &block
48
+ end
49
+
50
+ # Dispatches to any named view in a specific database
51
+ def view_on db, view_name, query={}, &block
52
+ view_name = view_name.to_s
53
+ view_slug = "#{name}/#{view_name}"
54
+ defaults = (self['views'][view_name] && self['views'][view_name]["couchrest-defaults"]) || {}
55
+ db.view(view_slug, defaults.merge(query), &block)
56
+ end
57
+
58
+ def search_on db, view_name, query={}, &block
59
+ view_slug = "#{name}/#{view_name}"
60
+ db.search(view_slug, query, &block)
61
+ end
62
+
63
+ def name
64
+ id.sub('_design/','') if id
65
+ end
66
+
67
+ def name= newname
68
+ self['_id'] = "_design/#{newname}"
69
+ end
70
+
71
+ def save
72
+ raise ArgumentError, "_design docs require a name" unless name && name.length > 0
73
+ super
74
+ end
75
+
76
+ private
77
+
78
+ # returns stored defaults if the there is a view named this in the design doc
79
+ def has_view?(view)
80
+ view = view.to_s
81
+ self['views'][view] &&
82
+ (self['views'][view]["couchrest-defaults"]||{})
83
+ end
84
+
85
+ def fetch_view view_name, opts, &block
86
+ database.view(view_name, opts, &block)
87
+ end
88
+
89
+ end
90
+
91
+ end