will-couchrest 0.32.1

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 (98) hide show
  1. data/LICENSE +176 -0
  2. data/README.md +165 -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/history.txt +65 -0
  17. data/lib/couchrest.rb +199 -0
  18. data/lib/couchrest/commands/generate.rb +71 -0
  19. data/lib/couchrest/commands/push.rb +103 -0
  20. data/lib/couchrest/core/adapters/restclient.rb +35 -0
  21. data/lib/couchrest/core/database.rb +317 -0
  22. data/lib/couchrest/core/design.rb +79 -0
  23. data/lib/couchrest/core/document.rb +83 -0
  24. data/lib/couchrest/core/http_abstraction.rb +48 -0
  25. data/lib/couchrest/core/response.rb +16 -0
  26. data/lib/couchrest/core/server.rb +88 -0
  27. data/lib/couchrest/core/view.rb +4 -0
  28. data/lib/couchrest/helper/pager.rb +103 -0
  29. data/lib/couchrest/helper/streamer.rb +44 -0
  30. data/lib/couchrest/helper/upgrade.rb +51 -0
  31. data/lib/couchrest/mixins.rb +4 -0
  32. data/lib/couchrest/mixins/attachments.rb +31 -0
  33. data/lib/couchrest/mixins/callbacks.rb +483 -0
  34. data/lib/couchrest/mixins/class_proxy.rb +116 -0
  35. data/lib/couchrest/mixins/collection.rb +225 -0
  36. data/lib/couchrest/mixins/design_doc.rb +103 -0
  37. data/lib/couchrest/mixins/document_queries.rb +82 -0
  38. data/lib/couchrest/mixins/extended_attachments.rb +74 -0
  39. data/lib/couchrest/mixins/extended_document_mixins.rb +8 -0
  40. data/lib/couchrest/mixins/properties.rb +158 -0
  41. data/lib/couchrest/mixins/validation.rb +257 -0
  42. data/lib/couchrest/mixins/views.rb +173 -0
  43. data/lib/couchrest/monkeypatches.rb +113 -0
  44. data/lib/couchrest/more/casted_model.rb +29 -0
  45. data/lib/couchrest/more/extended_document.rb +246 -0
  46. data/lib/couchrest/more/property.rb +40 -0
  47. data/lib/couchrest/support/blank.rb +42 -0
  48. data/lib/couchrest/support/class.rb +176 -0
  49. data/lib/couchrest/support/rails.rb +35 -0
  50. data/lib/couchrest/validation/auto_validate.rb +161 -0
  51. data/lib/couchrest/validation/contextual_validators.rb +78 -0
  52. data/lib/couchrest/validation/validation_errors.rb +125 -0
  53. data/lib/couchrest/validation/validators/absent_field_validator.rb +74 -0
  54. data/lib/couchrest/validation/validators/confirmation_validator.rb +99 -0
  55. data/lib/couchrest/validation/validators/format_validator.rb +117 -0
  56. data/lib/couchrest/validation/validators/formats/email.rb +66 -0
  57. data/lib/couchrest/validation/validators/formats/url.rb +43 -0
  58. data/lib/couchrest/validation/validators/generic_validator.rb +120 -0
  59. data/lib/couchrest/validation/validators/length_validator.rb +134 -0
  60. data/lib/couchrest/validation/validators/method_validator.rb +89 -0
  61. data/lib/couchrest/validation/validators/numeric_validator.rb +104 -0
  62. data/lib/couchrest/validation/validators/required_field_validator.rb +109 -0
  63. data/spec/couchrest/core/couchrest_spec.rb +201 -0
  64. data/spec/couchrest/core/database_spec.rb +700 -0
  65. data/spec/couchrest/core/design_spec.rb +138 -0
  66. data/spec/couchrest/core/document_spec.rb +267 -0
  67. data/spec/couchrest/core/server_spec.rb +35 -0
  68. data/spec/couchrest/helpers/pager_spec.rb +122 -0
  69. data/spec/couchrest/helpers/streamer_spec.rb +23 -0
  70. data/spec/couchrest/more/casted_extended_doc_spec.rb +75 -0
  71. data/spec/couchrest/more/casted_model_spec.rb +177 -0
  72. data/spec/couchrest/more/extended_doc_attachment_spec.rb +135 -0
  73. data/spec/couchrest/more/extended_doc_spec.rb +588 -0
  74. data/spec/couchrest/more/extended_doc_subclass_spec.rb +98 -0
  75. data/spec/couchrest/more/extended_doc_view_spec.rb +426 -0
  76. data/spec/couchrest/more/property_spec.rb +169 -0
  77. data/spec/fixtures/attachments/README +3 -0
  78. data/spec/fixtures/attachments/couchdb.png +0 -0
  79. data/spec/fixtures/attachments/test.html +11 -0
  80. data/spec/fixtures/more/article.rb +34 -0
  81. data/spec/fixtures/more/card.rb +22 -0
  82. data/spec/fixtures/more/cat.rb +18 -0
  83. data/spec/fixtures/more/course.rb +14 -0
  84. data/spec/fixtures/more/event.rb +6 -0
  85. data/spec/fixtures/more/invoice.rb +17 -0
  86. data/spec/fixtures/more/person.rb +8 -0
  87. data/spec/fixtures/more/question.rb +6 -0
  88. data/spec/fixtures/more/service.rb +12 -0
  89. data/spec/fixtures/views/lib.js +3 -0
  90. data/spec/fixtures/views/test_view/lib.js +3 -0
  91. data/spec/fixtures/views/test_view/only-map.js +4 -0
  92. data/spec/fixtures/views/test_view/test-map.js +3 -0
  93. data/spec/fixtures/views/test_view/test-reduce.js +3 -0
  94. data/spec/spec.opts +6 -0
  95. data/spec/spec_helper.rb +37 -0
  96. data/utils/remap.rb +27 -0
  97. data/utils/subset.rb +30 -0
  98. metadata +198 -0
@@ -0,0 +1,173 @@
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/couchrest/more/extended_doc_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
+ # returns stored defaults if the there is a view named this in the design doc
91
+ def has_view?(view)
92
+ view = view.to_s
93
+ design_doc && design_doc['views'] && design_doc['views'][view]
94
+ end
95
+
96
+ # Dispatches to any named view.
97
+ def view(name, query={}, &block)
98
+ db = query.delete(:database) || database
99
+ unless design_doc_fresh
100
+ refresh_design_doc_on(db)
101
+ end
102
+ query[:raw] = true if query[:reduce]
103
+ raw = query.delete(:raw)
104
+ fetch_view_with_docs(db, name, query, raw, &block)
105
+ end
106
+
107
+ # DEPRECATED
108
+ # user model_design_doc to retrieve the current design doc
109
+ def all_design_doc_versions(db = database)
110
+ db.documents :startkey => "_design/#{self.to_s}",
111
+ :endkey => "_design/#{self.to_s}-\u9999"
112
+ end
113
+
114
+ def model_design_doc(db = database)
115
+ begin
116
+ @model_design_doc = db.get("_design/#{self.to_s}")
117
+ rescue
118
+ nil
119
+ end
120
+ end
121
+
122
+ # Deletes the current design doc for the current class.
123
+ # Running it to early could mean that live code has to regenerate
124
+ # potentially large indexes.
125
+ def cleanup_design_docs!(db = database)
126
+ save_design_doc_on(db)
127
+ end
128
+
129
+ private
130
+
131
+ def fetch_view_with_docs(db, name, opts, raw=false, &block)
132
+ if raw || (opts.has_key?(:include_docs) && opts[:include_docs] == false)
133
+ fetch_view(db, name, opts, &block)
134
+ else
135
+ begin
136
+ if block.nil?
137
+ collection_proxy_for(design_doc, name, opts.merge({:include_docs => true}))
138
+ else
139
+ view = fetch_view db, name, opts.merge({:include_docs => true}), &block
140
+ view['rows'].collect{|r|new(r['doc'])} if view['rows']
141
+ end
142
+ rescue
143
+ # fallback for old versions of couchdb that don't
144
+ # have include_docs support
145
+ view = fetch_view(db, name, opts, &block)
146
+ view['rows'].collect{|r|new(db.get(r['id']))} if view['rows']
147
+ end
148
+ end
149
+ end
150
+
151
+ def fetch_view(db, view_name, opts, &block)
152
+ raise "A view needs a database to operate on (specify :database option, or use_database in the #{self.class} class)" unless db
153
+ retryable = true
154
+ begin
155
+ design_doc.view_on(db, view_name, opts, &block)
156
+ # the design doc may not have been saved yet on this database
157
+ rescue HttpAbstraction::ResourceNotFound => e
158
+ if retryable
159
+ save_design_doc_on(db)
160
+ retryable = false
161
+ retry
162
+ else
163
+ raise e
164
+ end
165
+ end
166
+ end
167
+
168
+ end # module ClassMethods
169
+
170
+
171
+ end
172
+ end
173
+ end
@@ -0,0 +1,113 @@
1
+ require File.join(File.dirname(__FILE__), 'support', 'class')
2
+ require File.join(File.dirname(__FILE__), 'support', 'blank')
3
+ require 'timeout'
4
+
5
+ # This file must be loaded after the JSON gem and any other library that beats up the Time class.
6
+ class Time
7
+ # This date format sorts lexicographically
8
+ # and is compatible with Javascript's <tt>new Date(time_string)</tt> constructor.
9
+ # Note this this format stores all dates in UTC so that collation
10
+ # order is preserved. (There's no longer a need to set <tt>ENV['TZ'] = 'UTC'</tt>
11
+ # in your application.)
12
+
13
+ def to_json(options = nil)
14
+ u = self.getutc
15
+ %("#{u.strftime("%Y/%m/%d %H:%M:%S +0000")}")
16
+ end
17
+
18
+ # Decodes the JSON time format to a UTC time.
19
+ # Based on Time.parse from ActiveSupport. ActiveSupport's version
20
+ # is more complete, returning a time in your current timezone,
21
+ # rather than keeping the time in UTC. YMMV.
22
+ # def self.parse string, fallback=nil
23
+ # d = DateTime.parse(string).new_offset
24
+ # self.utc(d.year, d.month, d.day, d.hour, d.min, d.sec)
25
+ # rescue
26
+ # fallback
27
+ # end
28
+ end
29
+
30
+ # Monkey patch for faster net/http io
31
+ if RUBY_VERSION.to_f < 1.9
32
+ class Net::BufferedIO #:nodoc:
33
+ alias :old_rbuf_fill :rbuf_fill
34
+ def rbuf_fill
35
+ if @io.respond_to?(:read_nonblock)
36
+ begin
37
+ @rbuf << @io.read_nonblock(65536)
38
+ rescue Errno::EWOULDBLOCK
39
+ if IO.select([@io], nil, nil, @read_timeout)
40
+ retry
41
+ else
42
+ raise Timeout::Error
43
+ end
44
+ end
45
+ else
46
+ timeout(@read_timeout) do
47
+ @rbuf << @io.sysread(65536)
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
53
+
54
+ # module RestClient
55
+ # # def self.copy(url, headers={})
56
+ # # Request.execute(:method => :copy,
57
+ # # :url => url,
58
+ # # :headers => headers)
59
+ # # end
60
+ #
61
+ # # class Request
62
+ # #
63
+ # # def establish_connection(uri)
64
+ # # Thread.current[:connection].finish if (Thread.current[:connection] && Thread.current[:connection].started?)
65
+ # # p net_http_class
66
+ # # net = net_http_class.new(uri.host, uri.port)
67
+ # # net.use_ssl = uri.is_a?(URI::HTTPS)
68
+ # # net.verify_mode = OpenSSL::SSL::VERIFY_NONE
69
+ # # Thread.current[:connection] = net
70
+ # # Thread.current[:connection].start
71
+ # # Thread.current[:connection]
72
+ # # end
73
+ # #
74
+ # # def transmit(uri, req, payload)
75
+ # # setup_credentials(req)
76
+ # #
77
+ # # Thread.current[:host] ||= uri.host
78
+ # # Thread.current[:port] ||= uri.port
79
+ # #
80
+ # # if (Thread.current[:connection].nil? || (Thread.current[:host] != uri.host))
81
+ # # p "establishing a connection"
82
+ # # establish_connection(uri)
83
+ # # end
84
+ # #
85
+ # # display_log request_log
86
+ # # http = Thread.current[:connection]
87
+ # # http.read_timeout = @timeout if @timeout
88
+ # #
89
+ # # begin
90
+ # # res = http.request(req, payload)
91
+ # # rescue
92
+ # # p "Net::HTTP connection failed, reconnecting"
93
+ # # establish_connection(uri)
94
+ # # http = Thread.current[:connection]
95
+ # # require 'ruby-debug'
96
+ # # req.body_stream = nil
97
+ # #
98
+ # # res = http.request(req, payload)
99
+ # # display_log response_log(res)
100
+ # # result res
101
+ # # else
102
+ # # display_log response_log(res)
103
+ # # process_result res
104
+ # # end
105
+ # #
106
+ # # rescue EOFError
107
+ # # raise RestClient::ServerBrokeConnection
108
+ # # rescue Timeout::Error
109
+ # # raise RestClient::RequestTimeout
110
+ # # end
111
+ # # end
112
+ #
113
+ # 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,246 @@
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
+ # Defines an instance and save it directly to the database
56
+ #
57
+ # ==== Returns
58
+ # returns the reloaded document
59
+ def self.create(options)
60
+ instance = new(options)
61
+ instance.create
62
+ instance
63
+ end
64
+
65
+ # Defines an instance and save it directly to the database
66
+ #
67
+ # ==== Returns
68
+ # returns the reloaded document or raises an exception
69
+ def self.create!(options)
70
+ instance = new(options)
71
+ instance.create!
72
+ instance
73
+ end
74
+
75
+ # Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
76
+ # on the document whenever saving occurs. CouchRest uses a pretty
77
+ # decent time format by default. See Time#to_json
78
+ def self.timestamps!
79
+ class_eval <<-EOS, __FILE__, __LINE__
80
+ property(:updated_at, :read_only => true, :cast_as => 'Time', :auto_validation => false)
81
+ property(:created_at, :read_only => true, :cast_as => 'Time', :auto_validation => false)
82
+
83
+ save_callback :before do |object|
84
+ object['updated_at'] = Time.now
85
+ object['created_at'] = object['updated_at'] if object.new_document?
86
+ end
87
+ EOS
88
+ end
89
+
90
+ # Name a method that will be called before the document is first saved,
91
+ # which returns a string to be used for the document's <tt>_id</tt>.
92
+ # Because CouchDB enforces a constraint that each id must be unique,
93
+ # this can be used to enforce eg: uniq usernames. Note that this id
94
+ # must be globally unique across all document types which share a
95
+ # database, so if you'd like to scope uniqueness to this class, you
96
+ # should use the class name as part of the unique id.
97
+ def self.unique_id method = nil, &block
98
+ if method
99
+ define_method :set_unique_id do
100
+ self['_id'] ||= self.send(method)
101
+ end
102
+ elsif block
103
+ define_method :set_unique_id do
104
+ uniqid = block.call(self)
105
+ raise ArgumentError, "unique_id block must not return nil" if uniqid.nil?
106
+ self['_id'] ||= uniqid
107
+ end
108
+ end
109
+ end
110
+
111
+ # Temp solution to make the view_by methods available
112
+ def self.method_missing(m, *args, &block)
113
+ if has_view?(m)
114
+ query = args.shift || {}
115
+ view(m, query, *args, &block)
116
+ else
117
+ super
118
+ end
119
+ end
120
+
121
+ ### instance methods
122
+
123
+ # Returns the Class properties
124
+ #
125
+ # ==== Returns
126
+ # Array:: the list of properties for the instance
127
+ def properties
128
+ self.class.properties
129
+ end
130
+
131
+ # Takes a hash as argument, and applies the values by using writer methods
132
+ # for each key. It doesn't save the document at the end. Raises a NoMethodError if the corresponding methods are
133
+ # missing. In case of error, no attributes are changed.
134
+ def update_attributes_without_saving(hash)
135
+ hash.each do |k, v|
136
+ raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=")
137
+ end
138
+ hash.each do |k, v|
139
+ self.send("#{k}=",v)
140
+ end
141
+ end
142
+
143
+ # Takes a hash as argument, and applies the values by using writer methods
144
+ # for each key. Raises a NoMethodError if the corresponding methods are
145
+ # missing. In case of error, no attributes are changed.
146
+ def update_attributes(hash)
147
+ update_attributes_without_saving hash
148
+ save
149
+ end
150
+
151
+ # for compatibility with old-school frameworks
152
+ alias :new_record? :new_document?
153
+
154
+ # Trigger the callbacks (before, after, around)
155
+ # and create the document
156
+ # It's important to have a create callback since you can't check if a document
157
+ # was new after you saved it
158
+ #
159
+ # When creating a document, both the create and the save callbacks will be triggered.
160
+ def create(bulk = false)
161
+ caught = catch(:halt) do
162
+ _run_create_callbacks do
163
+ _run_save_callbacks do
164
+ create_without_callbacks(bulk)
165
+ end
166
+ end
167
+ end
168
+ end
169
+
170
+ # unlike save, create returns the newly created document
171
+ def create_without_callbacks(bulk =false)
172
+ raise ArgumentError, "a document requires a database to be created to (The document or the #{self.class} default database were not set)" unless database
173
+ set_unique_id if new_document? && self.respond_to?(:set_unique_id)
174
+ result = database.save_doc(self, bulk)
175
+ (result["ok"] == true) ? self : false
176
+ end
177
+
178
+ # Creates the document in the db. Raises an exception
179
+ # if the document is not created properly.
180
+ def create!
181
+ raise "#{self.inspect} failed to save" unless self.create
182
+ end
183
+
184
+ # Trigger the callbacks (before, after, around)
185
+ # only if the document isn't new
186
+ def update(bulk = false)
187
+ caught = catch(:halt) do
188
+ if self.new_document?
189
+ save(bulk)
190
+ else
191
+ _run_update_callbacks do
192
+ _run_save_callbacks do
193
+ save_without_callbacks(bulk)
194
+ end
195
+ end
196
+ end
197
+ end
198
+ end
199
+
200
+ # Trigger the callbacks (before, after, around)
201
+ # and save the document
202
+ def save(bulk = false)
203
+ caught = catch(:halt) do
204
+ if self.new_document?
205
+ _run_save_callbacks do
206
+ save_without_callbacks(bulk)
207
+ end
208
+ else
209
+ update(bulk)
210
+ end
211
+ end
212
+ end
213
+
214
+ # Overridden to set the unique ID.
215
+ # Returns a boolean value
216
+ def save_without_callbacks(bulk = false)
217
+ raise ArgumentError, "a document requires a database to be saved to (The document or the #{self.class} default database were not set)" unless database
218
+ set_unique_id if new_document? && self.respond_to?(:set_unique_id)
219
+ result = database.save_doc(self, bulk)
220
+ result["ok"] == true
221
+ end
222
+
223
+ # Saves the document to the db using save. Raises an exception
224
+ # if the document is not saved properly.
225
+ def save!
226
+ raise "#{self.inspect} failed to save" unless self.save
227
+ end
228
+
229
+ # Deletes the document from the database. Runs the :destroy callbacks.
230
+ # Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
231
+ # document to be saved to a new <tt>_id</tt>.
232
+ def destroy(bulk=false)
233
+ caught = catch(:halt) do
234
+ _run_destroy_callbacks do
235
+ result = database.delete_doc(self, bulk)
236
+ if result['ok']
237
+ self.delete('_rev')
238
+ self.delete('_id')
239
+ end
240
+ result['ok']
241
+ end
242
+ end
243
+ end
244
+
245
+ end
246
+ end