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,211 @@
1
+ module CouchRest
2
+ module Mixins
3
+ module Views
4
+
5
+ def self.included(base)
6
+ base.extend(ClassMethods)
7
+ end
8
+
9
+ module ClassMethods
10
+ # Define a CouchDB view. The name of the view will be the concatenation
11
+ # of <tt>by</tt> and the keys joined by <tt>_and_</tt>
12
+ #
13
+ # ==== Example views:
14
+ #
15
+ # class Post
16
+ # # view with default options
17
+ # # query with Post.by_date
18
+ # view_by :date, :descending => true
19
+ #
20
+ # # view with compound sort-keys
21
+ # # query with Post.by_user_id_and_date
22
+ # view_by :user_id, :date
23
+ #
24
+ # # view with custom map/reduce functions
25
+ # # query with Post.by_tags :reduce => true
26
+ # view_by :tags,
27
+ # :map =>
28
+ # "function(doc) {
29
+ # if (doc['couchrest-type'] == 'Post' && doc.tags) {
30
+ # doc.tags.forEach(function(tag){
31
+ # emit(doc.tag, 1);
32
+ # });
33
+ # }
34
+ # }",
35
+ # :reduce =>
36
+ # "function(keys, values, rereduce) {
37
+ # return sum(values);
38
+ # }"
39
+ # end
40
+ #
41
+ # <tt>view_by :date</tt> will create a view defined by this Javascript
42
+ # function:
43
+ #
44
+ # function(doc) {
45
+ # if (doc['couchrest-type'] == 'Post' && doc.date) {
46
+ # emit(doc.date, null);
47
+ # }
48
+ # }
49
+ #
50
+ # It can be queried by calling <tt>Post.by_date</tt> which accepts all
51
+ # valid options for CouchRest::Database#view. In addition, calling with
52
+ # the <tt>:raw => true</tt> option will return the view rows
53
+ # themselves. By default <tt>Post.by_date</tt> will return the
54
+ # documents included in the generated view.
55
+ #
56
+ # Calling with :database => [instance of CouchRest::Database] will
57
+ # send the query to a specific database, otherwise it will go to
58
+ # the model's default database (use_database)
59
+ #
60
+ # CouchRest::Database#view options can be applied at view definition
61
+ # time as defaults, and they will be curried and used at view query
62
+ # time. Or they can be overridden at query time.
63
+ #
64
+ # Custom views can be queried with <tt>:reduce => true</tt> to return
65
+ # reduce results. The default for custom views is to query with
66
+ # <tt>:reduce => false</tt>.
67
+ #
68
+ # Views are generated (on a per-model basis) lazily on first-access.
69
+ # This means that if you are deploying changes to a view, the views for
70
+ # that model won't be available until generation is complete. This can
71
+ # take some time with large databases. Strategies are in the works.
72
+ #
73
+ # To understand the capabilities of this view system more completely,
74
+ # it is recommended that you read the RSpec file at
75
+ # <tt>spec/core/model_spec.rb</tt>.
76
+
77
+ def view_by(*keys)
78
+ opts = keys.pop if keys.last.is_a?(Hash)
79
+ opts ||= {}
80
+ ducktype = opts.delete(:ducktype)
81
+ unless ducktype || opts[:map]
82
+ opts[:guards] ||= []
83
+ opts[:guards].push "(doc['couchrest-type'] == '#{self.to_s}')"
84
+ end
85
+ keys.push opts
86
+ self.design_doc.view_by(*keys)
87
+ self.design_doc_fresh = false
88
+ end
89
+
90
+ # FIXME
91
+ # Define search view
92
+ def search_by(*keys)
93
+ self.refresh_design_doc
94
+ self.design_doc.search_by(*keys)
95
+ end
96
+
97
+ # returns stored defaults if the there is a view named this in the design doc
98
+ def has_view?(view)
99
+ view = view.to_s
100
+ design_doc && design_doc['views'] && design_doc['views'][view]
101
+ end
102
+
103
+ # returns stored defaults if there is a search view named like this in the design doc
104
+ def has_search_view?(view)
105
+ view = view.to_s.sub(/^search_/, '')
106
+ design_doc && design_doc['fulltext'] && design_doc['fulltext'][view]
107
+ end
108
+
109
+ # Dispatches to any named view.
110
+ def view(name, query={}, &block)
111
+ unless design_doc_fresh
112
+ refresh_design_doc
113
+ end
114
+ query[:raw] = true if query[:reduce]
115
+ db = query.delete(:database) || database
116
+ raw = query.delete(:raw)
117
+ fetch_view_with_docs(db, name, query, raw, &block)
118
+ end
119
+
120
+ # Dispatch to a named search view
121
+ def search_view(name, query="", opts={}, &block)
122
+ name = name.to_s.sub(/^search_/, '')
123
+ db = opts.delete(:database) || database
124
+ opts[:q] = query
125
+ fetch_search_view_with_docs(db, name, opts, &block)
126
+ end
127
+
128
+ # DEPRECATED
129
+ # user model_design_doc to retrieve the current design doc
130
+ def all_design_doc_versions(db = database)
131
+ db.documents :startkey => "_design/#{self.to_s}",
132
+ :endkey => "_design/#{self.to_s}-\u9999"
133
+ end
134
+
135
+ def model_design_doc(db = database)
136
+ begin
137
+ @model_design_doc = db.get("_design/#{self.to_s}")
138
+ rescue
139
+ nil
140
+ end
141
+ end
142
+
143
+ # Deletes the current design doc for the current class.
144
+ # Running it to early could mean that live code has to regenerate
145
+ # potentially large indexes.
146
+ def cleanup_design_docs!(db = database)
147
+ save_design_doc_on(db)
148
+ # db.refresh_design_doc
149
+ # db.save_design_doc
150
+ # design_doc = model_design_doc(db)
151
+ # if design_doc
152
+ # db.delete_doc(design_doc)
153
+ # else
154
+ # false
155
+ # end
156
+ end
157
+
158
+ private
159
+
160
+ def fetch_search_view_with_docs(db, name, opts, &block)
161
+ #if opts.has_key?(:include_docs) && opts[:include_docs] == false
162
+ #fetch_search_view(db, name, opts, &block)
163
+ #end
164
+
165
+ # FIXME try to handle pagination with the same process as views.
166
+ design_doc.search_on(db, name, opts, &block)
167
+ end
168
+
169
+ def fetch_view_with_docs(db, name, opts, raw=false, &block)
170
+ if raw || (opts.has_key?(:include_docs) && opts[:include_docs] == false)
171
+ fetch_view(db, name, opts, &block)
172
+ else
173
+ begin
174
+ if block.nil?
175
+ collection_proxy_for(design_doc, name, opts.merge({:include_docs => true}))
176
+ else
177
+ view = fetch_view db, name, opts.merge({:include_docs => true}), &block
178
+ view['rows'].collect{|r|new(r['doc'])} if view['rows']
179
+ end
180
+ rescue
181
+ # fallback for old versions of couchdb that don't
182
+ # have include_docs support
183
+ view = fetch_view(db, name, opts, &block)
184
+ view['rows'].collect{|r|new(db.get(r['id']))} if view['rows']
185
+ end
186
+ end
187
+ end
188
+
189
+ def fetch_view(db, view_name, opts, &block)
190
+ raise "A view needs a database to operate on (specify :database option, or use_database in the #{self.class} class)" unless db
191
+ retryable = true
192
+ begin
193
+ design_doc.view_on(db, view_name, opts, &block)
194
+ # the design doc may not have been saved yet on this database
195
+ rescue RestClient::ResourceNotFound => e
196
+ if retryable
197
+ save_design_doc_on(db)
198
+ retryable = false
199
+ retry
200
+ else
201
+ raise e
202
+ end
203
+ end
204
+ end
205
+
206
+ end # module ClassMethods
207
+
208
+
209
+ end
210
+ end
211
+ end
@@ -0,0 +1,112 @@
1
+ require File.join(File.dirname(__FILE__), 'support', 'class')
2
+ require File.join(File.dirname(__FILE__), 'support', 'blank')
3
+
4
+ # This file must be loaded after the JSON gem and any other library that beats up the Time class.
5
+ class Time
6
+ # This date format sorts lexicographically
7
+ # and is compatible with Javascript's <tt>new Date(time_string)</tt> constructor.
8
+ # Note this this format stores all dates in UTC so that collation
9
+ # order is preserved. (There's no longer a need to set <tt>ENV['TZ'] = 'UTC'</tt>
10
+ # in your application.)
11
+
12
+ def to_json(options = nil)
13
+ u = self.getutc
14
+ %("#{u.strftime("%Y/%m/%d %H:%M:%S +0000")}")
15
+ end
16
+
17
+ # Decodes the JSON time format to a UTC time.
18
+ # Based on Time.parse from ActiveSupport. ActiveSupport's version
19
+ # is more complete, returning a time in your current timezone,
20
+ # rather than keeping the time in UTC. YMMV.
21
+ # def self.parse string, fallback=nil
22
+ # d = DateTime.parse(string).new_offset
23
+ # self.utc(d.year, d.month, d.day, d.hour, d.min, d.sec)
24
+ # rescue
25
+ # fallback
26
+ # end
27
+ end
28
+
29
+ # Monkey patch for faster net/http io
30
+ if RUBY_VERSION.to_f < 1.9
31
+ class Net::BufferedIO #:nodoc:
32
+ alias :old_rbuf_fill :rbuf_fill
33
+ def rbuf_fill
34
+ if @io.respond_to?(:read_nonblock)
35
+ begin
36
+ @rbuf << @io.read_nonblock(65536)
37
+ rescue Errno::EWOULDBLOCK
38
+ if IO.select([@io], nil, nil, @read_timeout)
39
+ retry
40
+ else
41
+ raise Timeout::TimeoutError
42
+ end
43
+ end
44
+ else
45
+ timeout(@read_timeout) do
46
+ @rbuf << @io.sysread(65536)
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
52
+
53
+ module RestClient
54
+ def self.copy(url, headers={})
55
+ Request.execute(:method => :copy,
56
+ :url => url,
57
+ :headers => headers)
58
+ end
59
+
60
+ # class Request
61
+ #
62
+ # def establish_connection(uri)
63
+ # Thread.current[:connection].finish if (Thread.current[:connection] && Thread.current[:connection].started?)
64
+ # p net_http_class
65
+ # net = net_http_class.new(uri.host, uri.port)
66
+ # net.use_ssl = uri.is_a?(URI::HTTPS)
67
+ # net.verify_mode = OpenSSL::SSL::VERIFY_NONE
68
+ # Thread.current[:connection] = net
69
+ # Thread.current[:connection].start
70
+ # Thread.current[:connection]
71
+ # end
72
+ #
73
+ # def transmit(uri, req, payload)
74
+ # setup_credentials(req)
75
+ #
76
+ # Thread.current[:host] ||= uri.host
77
+ # Thread.current[:port] ||= uri.port
78
+ #
79
+ # if (Thread.current[:connection].nil? || (Thread.current[:host] != uri.host))
80
+ # p "establishing a connection"
81
+ # establish_connection(uri)
82
+ # end
83
+ #
84
+ # display_log request_log
85
+ # http = Thread.current[:connection]
86
+ # http.read_timeout = @timeout if @timeout
87
+ #
88
+ # begin
89
+ # res = http.request(req, payload)
90
+ # rescue
91
+ # p "Net::HTTP connection failed, reconnecting"
92
+ # establish_connection(uri)
93
+ # http = Thread.current[:connection]
94
+ # require 'ruby-debug'
95
+ # req.body_stream = nil
96
+ #
97
+ # res = http.request(req, payload)
98
+ # display_log response_log(res)
99
+ # result res
100
+ # else
101
+ # display_log response_log(res)
102
+ # process_result res
103
+ # end
104
+ #
105
+ # rescue EOFError
106
+ # raise RestClient::ServerBrokeConnection
107
+ # rescue Timeout::Error
108
+ # raise RestClient::RequestTimeout
109
+ # end
110
+ # end
111
+
112
+ end
@@ -0,0 +1,29 @@
1
+ require File.join(File.dirname(__FILE__), '..', 'mixins', 'properties')
2
+
3
+ module CouchRest
4
+ module CastedModel
5
+
6
+ def self.included(base)
7
+ base.send(:include, CouchRest::Mixins::Properties)
8
+ base.send(:attr_accessor, :casted_by)
9
+ end
10
+
11
+ def initialize(keys={})
12
+ raise StandardError unless self.is_a? Hash
13
+ apply_defaults # defined in CouchRest::Mixins::Properties
14
+ super()
15
+ keys.each do |k,v|
16
+ self[k.to_s] = v
17
+ end if keys
18
+ cast_keys # defined in CouchRest::Mixins::Properties
19
+ end
20
+
21
+ def []= key, value
22
+ super(key.to_s, value)
23
+ end
24
+
25
+ def [] key
26
+ super(key.to_s)
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,232 @@
1
+ require 'mime/types'
2
+ require File.join(File.dirname(__FILE__), "property")
3
+ require File.join(File.dirname(__FILE__), '..', 'mixins', 'extended_document_mixins')
4
+ require "enumerator"
5
+
6
+ module CouchRest
7
+
8
+ # Same as CouchRest::Document but with properties and validations
9
+ class ExtendedDocument < Document
10
+ include CouchRest::Callbacks
11
+ include CouchRest::Mixins::DocumentQueries
12
+ include CouchRest::Mixins::Views
13
+ include CouchRest::Mixins::DesignDoc
14
+ include CouchRest::Mixins::ExtendedAttachments
15
+ include CouchRest::Mixins::ClassProxy
16
+ include CouchRest::Mixins::Collection
17
+
18
+ def self.subclasses
19
+ @subclasses ||= []
20
+ end
21
+
22
+ def self.inherited(subklass)
23
+ subklass.send(:include, CouchRest::Mixins::Properties)
24
+ subklass.class_eval <<-EOS, __FILE__, __LINE__
25
+ def self.inherited(subklass)
26
+ subklass.properties = self.properties.dup
27
+ end
28
+ EOS
29
+ subclasses << subklass
30
+ end
31
+
32
+ # Accessors
33
+ attr_accessor :casted_by
34
+
35
+ # Callbacks
36
+ define_callbacks :create
37
+ define_callbacks :save
38
+ define_callbacks :update
39
+ define_callbacks :destroy
40
+
41
+ def initialize(passed_keys={})
42
+ apply_defaults # defined in CouchRest::Mixins::Properties
43
+ passed_keys.each do |k,v|
44
+ if self.respond_to?("#{k}=")
45
+ self.send("#{k}=", passed_keys.delete(k))
46
+ end
47
+ end if passed_keys
48
+ super
49
+ cast_keys # defined in CouchRest::Mixins::Properties
50
+ unless self['_id'] && self['_rev']
51
+ self['couchrest-type'] = self.class.to_s
52
+ end
53
+ end
54
+
55
+
56
+
57
+
58
+ # Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
59
+ # on the document whenever saving occurs. CouchRest uses a pretty
60
+ # decent time format by default. See Time#to_json
61
+ def self.timestamps!
62
+ class_eval <<-EOS, __FILE__, __LINE__
63
+ property(:updated_at, :read_only => true, :cast_as => 'Time', :auto_validation => false)
64
+ property(:created_at, :read_only => true, :cast_as => 'Time', :auto_validation => false)
65
+
66
+ save_callback :before do |object|
67
+ object['updated_at'] = Time.now
68
+ object['created_at'] = object['updated_at'] if object.new_document?
69
+ end
70
+ EOS
71
+ end
72
+
73
+ # Name a method that will be called before the document is first saved,
74
+ # which returns a string to be used for the document's <tt>_id</tt>.
75
+ # Because CouchDB enforces a constraint that each id must be unique,
76
+ # this can be used to enforce eg: uniq usernames. Note that this id
77
+ # must be globally unique across all document types which share a
78
+ # database, so if you'd like to scope uniqueness to this class, you
79
+ # should use the class name as part of the unique id.
80
+ def self.unique_id method = nil, &block
81
+ if method
82
+ define_method :set_unique_id do
83
+ self['_id'] ||= self.send(method)
84
+ end
85
+ elsif block
86
+ define_method :set_unique_id do
87
+ uniqid = block.call(self)
88
+ raise ArgumentError, "unique_id block must not return nil" if uniqid.nil?
89
+ self['_id'] ||= uniqid
90
+ end
91
+ end
92
+ end
93
+
94
+ # Temp solution to make the view_by methods available
95
+ def self.method_missing(m, *args, &block)
96
+ if has_view?(m)
97
+ query = args.shift || {}
98
+ view(m, query, *args, &block)
99
+ elsif has_search_view?(m)
100
+ query = args.shift || {}
101
+ search_view(m, query, *args, &block)
102
+ else
103
+ super
104
+ end
105
+ end
106
+
107
+ ### instance methods
108
+
109
+ # Returns the Class properties
110
+ #
111
+ # ==== Returns
112
+ # Array:: the list of properties for the instance
113
+ def properties
114
+ self.class.properties
115
+ end
116
+
117
+ # Takes a hash as argument, and applies the values by using writer methods
118
+ # for each key. It doesn't save the document at the end. Raises a NoMethodError if the corresponding methods are
119
+ # missing. In case of error, no attributes are changed.
120
+ def update_attributes_without_saving(hash)
121
+ hash.each do |k, v|
122
+ raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=")
123
+ end
124
+ hash.each do |k, v|
125
+ self.send("#{k}=",v)
126
+ end
127
+ end
128
+
129
+ # Takes a hash as argument, and applies the values by using writer methods
130
+ # for each key. Raises a NoMethodError if the corresponding methods are
131
+ # missing. In case of error, no attributes are changed.
132
+ def update_attributes(hash)
133
+ update_attributes_without_saving hash
134
+ save
135
+ end
136
+
137
+ # for compatibility with old-school frameworks
138
+ alias :new_record? :new_document?
139
+
140
+ # Trigger the callbacks (before, after, around)
141
+ # and create the document
142
+ # It's important to have a create callback since you can't check if a document
143
+ # was new after you saved it
144
+ #
145
+ # When creating a document, both the create and the save callbacks will be triggered.
146
+ def create(bulk = false)
147
+ caught = catch(:halt) do
148
+ _run_create_callbacks do
149
+ _run_save_callbacks do
150
+ create_without_callbacks(bulk)
151
+ end
152
+ end
153
+ end
154
+ end
155
+
156
+ # unlike save, create returns the newly created document
157
+ def create_without_callbacks(bulk =false)
158
+ raise ArgumentError, "a document requires a database to be created to (The document or the #{self.class} default database were not set)" unless database
159
+ set_unique_id if new_document? && self.respond_to?(:set_unique_id)
160
+ result = database.save_doc(self, bulk)
161
+ (result["ok"] == true) ? self : false
162
+ end
163
+
164
+ # Creates the document in the db. Raises an exception
165
+ # if the document is not created properly.
166
+ def create!
167
+ raise "#{self.inspect} failed to save" unless self.create
168
+ end
169
+
170
+ # Trigger the callbacks (before, after, around)
171
+ # only if the document isn't new
172
+ def update(bulk = false)
173
+ caught = catch(:halt) do
174
+ if self.new_document?
175
+ save(bulk)
176
+ else
177
+ _run_update_callbacks do
178
+ _run_save_callbacks do
179
+ save_without_callbacks(bulk)
180
+ end
181
+ end
182
+ end
183
+ end
184
+ end
185
+
186
+ # Trigger the callbacks (before, after, around)
187
+ # and save the document
188
+ def save(bulk = false)
189
+ caught = catch(:halt) do
190
+ if self.new_document?
191
+ _run_save_callbacks do
192
+ save_without_callbacks(bulk)
193
+ end
194
+ else
195
+ update(bulk)
196
+ end
197
+ end
198
+ end
199
+
200
+ # Overridden to set the unique ID.
201
+ # Returns a boolean value
202
+ def save_without_callbacks(bulk = false)
203
+ raise ArgumentError, "a document requires a database to be saved to (The document or the #{self.class} default database were not set)" unless database
204
+ set_unique_id if new_document? && self.respond_to?(:set_unique_id)
205
+ result = database.save_doc(self, bulk)
206
+ result["ok"] == true
207
+ end
208
+
209
+ # Saves the document to the db using save. Raises an exception
210
+ # if the document is not saved properly.
211
+ def save!
212
+ raise "#{self.inspect} failed to save" unless self.save
213
+ end
214
+
215
+ # Deletes the document from the database. Runs the :destroy callbacks.
216
+ # Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
217
+ # document to be saved to a new <tt>_id</tt>.
218
+ def destroy(bulk=false)
219
+ caught = catch(:halt) do
220
+ _run_destroy_callbacks do
221
+ result = database.delete_doc(self, bulk)
222
+ if result['ok']
223
+ self.delete('_rev')
224
+ self.delete('_id')
225
+ end
226
+ result['ok']
227
+ end
228
+ end
229
+ end
230
+
231
+ end
232
+ end