norr-couchrest 0.30

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 (96) hide show
  1. data/LICENSE +176 -0
  2. data/README.md +117 -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 +19 -0
  17. data/lib/couchrest.rb +198 -0
  18. data/lib/couchrest/commands/generate.rb +71 -0
  19. data/lib/couchrest/commands/push.rb +103 -0
  20. data/lib/couchrest/core/database.rb +320 -0
  21. data/lib/couchrest/core/design.rb +79 -0
  22. data/lib/couchrest/core/document.rb +87 -0
  23. data/lib/couchrest/core/response.rb +16 -0
  24. data/lib/couchrest/core/server.rb +88 -0
  25. data/lib/couchrest/core/view.rb +4 -0
  26. data/lib/couchrest/helper/pager.rb +103 -0
  27. data/lib/couchrest/helper/streamer.rb +44 -0
  28. data/lib/couchrest/helper/upgrade.rb +51 -0
  29. data/lib/couchrest/mixins.rb +4 -0
  30. data/lib/couchrest/mixins/attachments.rb +31 -0
  31. data/lib/couchrest/mixins/callbacks.rb +483 -0
  32. data/lib/couchrest/mixins/class_proxy.rb +112 -0
  33. data/lib/couchrest/mixins/collection.rb +220 -0
  34. data/lib/couchrest/mixins/design_doc.rb +101 -0
  35. data/lib/couchrest/mixins/document_queries.rb +53 -0
  36. data/lib/couchrest/mixins/extended_attachments.rb +74 -0
  37. data/lib/couchrest/mixins/extended_document_mixins.rb +8 -0
  38. data/lib/couchrest/mixins/properties.rb +147 -0
  39. data/lib/couchrest/mixins/validation.rb +257 -0
  40. data/lib/couchrest/mixins/views.rb +181 -0
  41. data/lib/couchrest/monkeypatches.rb +113 -0
  42. data/lib/couchrest/more/casted_model.rb +29 -0
  43. data/lib/couchrest/more/extended_document.rb +229 -0
  44. data/lib/couchrest/more/property.rb +40 -0
  45. data/lib/couchrest/support/blank.rb +42 -0
  46. data/lib/couchrest/support/class.rb +176 -0
  47. data/lib/couchrest/support/rails.rb +35 -0
  48. data/lib/couchrest/validation/auto_validate.rb +161 -0
  49. data/lib/couchrest/validation/contextual_validators.rb +78 -0
  50. data/lib/couchrest/validation/validation_errors.rb +118 -0
  51. data/lib/couchrest/validation/validators/absent_field_validator.rb +74 -0
  52. data/lib/couchrest/validation/validators/confirmation_validator.rb +99 -0
  53. data/lib/couchrest/validation/validators/format_validator.rb +117 -0
  54. data/lib/couchrest/validation/validators/formats/email.rb +66 -0
  55. data/lib/couchrest/validation/validators/formats/url.rb +43 -0
  56. data/lib/couchrest/validation/validators/generic_validator.rb +120 -0
  57. data/lib/couchrest/validation/validators/length_validator.rb +134 -0
  58. data/lib/couchrest/validation/validators/method_validator.rb +89 -0
  59. data/lib/couchrest/validation/validators/numeric_validator.rb +104 -0
  60. data/lib/couchrest/validation/validators/required_field_validator.rb +109 -0
  61. data/spec/couchrest/core/couchrest_spec.rb +201 -0
  62. data/spec/couchrest/core/database_spec.rb +700 -0
  63. data/spec/couchrest/core/design_spec.rb +138 -0
  64. data/spec/couchrest/core/document_spec.rb +267 -0
  65. data/spec/couchrest/core/server_spec.rb +35 -0
  66. data/spec/couchrest/helpers/pager_spec.rb +122 -0
  67. data/spec/couchrest/helpers/streamer_spec.rb +23 -0
  68. data/spec/couchrest/more/casted_extended_doc_spec.rb +75 -0
  69. data/spec/couchrest/more/casted_model_spec.rb +177 -0
  70. data/spec/couchrest/more/extended_doc_attachment_spec.rb +135 -0
  71. data/spec/couchrest/more/extended_doc_spec.rb +563 -0
  72. data/spec/couchrest/more/extended_doc_subclass_spec.rb +98 -0
  73. data/spec/couchrest/more/extended_doc_view_spec.rb +414 -0
  74. data/spec/couchrest/more/property_spec.rb +146 -0
  75. data/spec/fixtures/attachments/README +3 -0
  76. data/spec/fixtures/attachments/couchdb.png +0 -0
  77. data/spec/fixtures/attachments/test.html +11 -0
  78. data/spec/fixtures/more/article.rb +34 -0
  79. data/spec/fixtures/more/card.rb +22 -0
  80. data/spec/fixtures/more/cat.rb +18 -0
  81. data/spec/fixtures/more/course.rb +14 -0
  82. data/spec/fixtures/more/event.rb +6 -0
  83. data/spec/fixtures/more/invoice.rb +17 -0
  84. data/spec/fixtures/more/person.rb +8 -0
  85. data/spec/fixtures/more/question.rb +6 -0
  86. data/spec/fixtures/more/service.rb +12 -0
  87. data/spec/fixtures/views/lib.js +3 -0
  88. data/spec/fixtures/views/test_view/lib.js +3 -0
  89. data/spec/fixtures/views/test_view/only-map.js +4 -0
  90. data/spec/fixtures/views/test_view/test-map.js +3 -0
  91. data/spec/fixtures/views/test_view/test-reduce.js +3 -0
  92. data/spec/spec.opts +6 -0
  93. data/spec/spec_helper.rb +37 -0
  94. data/utils/remap.rb +27 -0
  95. data/utils/subset.rb +30 -0
  96. metadata +194 -0
@@ -0,0 +1,181 @@
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
+ # 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
+ unless design_doc_fresh
99
+ refresh_design_doc
100
+ end
101
+ query[:raw] = true if query[:reduce]
102
+ db = query.delete(:database) || database
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
+ # db.refresh_design_doc
128
+ # db.save_design_doc
129
+ # design_doc = model_design_doc(db)
130
+ # if design_doc
131
+ # db.delete_doc(design_doc)
132
+ # else
133
+ # false
134
+ # end
135
+ end
136
+
137
+ private
138
+
139
+ def fetch_view_with_docs(db, name, opts, raw=false, &block)
140
+ if raw || (opts.has_key?(:include_docs) && opts[:include_docs] == false)
141
+ fetch_view(db, name, opts, &block)
142
+ else
143
+ begin
144
+ if block.nil?
145
+ collection_proxy_for(design_doc, name, opts.merge({:include_docs => true}))
146
+ else
147
+ view = fetch_view db, name, opts.merge({:include_docs => true}), &block
148
+ view['rows'].collect{|r|new(r['doc'])} if view['rows']
149
+ end
150
+ rescue
151
+ # fallback for old versions of couchdb that don't
152
+ # have include_docs support
153
+ view = fetch_view(db, name, opts, &block)
154
+ view['rows'].collect{|r|new(db.get(r['id']))} if view['rows']
155
+ end
156
+ end
157
+ end
158
+
159
+ def fetch_view(db, view_name, opts, &block)
160
+ raise "A view needs a database to operate on (specify :database option, or use_database in the #{self.class} class)" unless db
161
+ retryable = true
162
+ begin
163
+ design_doc.view_on(db, view_name, opts, &block)
164
+ # the design doc may not have been saved yet on this database
165
+ rescue RestClient::ResourceNotFound => e
166
+ if retryable
167
+ save_design_doc_on(db)
168
+ retryable = false
169
+ retry
170
+ else
171
+ raise e
172
+ end
173
+ end
174
+ end
175
+
176
+ end # module ClassMethods
177
+
178
+
179
+ end
180
+ end
181
+ 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,229 @@
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
+ else
100
+ super
101
+ end
102
+ end
103
+
104
+ ### instance methods
105
+
106
+ # Returns the Class properties
107
+ #
108
+ # ==== Returns
109
+ # Array:: the list of properties for the instance
110
+ def properties
111
+ self.class.properties
112
+ end
113
+
114
+ # Takes a hash as argument, and applies the values by using writer methods
115
+ # for each key. It doesn't save the document at the end. Raises a NoMethodError if the corresponding methods are
116
+ # missing. In case of error, no attributes are changed.
117
+ def update_attributes_without_saving(hash)
118
+ hash.each do |k, v|
119
+ raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=")
120
+ end
121
+ hash.each do |k, v|
122
+ self.send("#{k}=",v)
123
+ end
124
+ end
125
+
126
+ # Takes a hash as argument, and applies the values by using writer methods
127
+ # for each key. Raises a NoMethodError if the corresponding methods are
128
+ # missing. In case of error, no attributes are changed.
129
+ def update_attributes(hash)
130
+ update_attributes_without_saving hash
131
+ save
132
+ end
133
+
134
+ # for compatibility with old-school frameworks
135
+ alias :new_record? :new_document?
136
+
137
+ # Trigger the callbacks (before, after, around)
138
+ # and create the document
139
+ # It's important to have a create callback since you can't check if a document
140
+ # was new after you saved it
141
+ #
142
+ # When creating a document, both the create and the save callbacks will be triggered.
143
+ def create(bulk = false)
144
+ caught = catch(:halt) do
145
+ _run_create_callbacks do
146
+ _run_save_callbacks do
147
+ create_without_callbacks(bulk)
148
+ end
149
+ end
150
+ end
151
+ end
152
+
153
+ # unlike save, create returns the newly created document
154
+ def create_without_callbacks(bulk =false)
155
+ raise ArgumentError, "a document requires a database to be created to (The document or the #{self.class} default database were not set)" unless database
156
+ set_unique_id if new_document? && self.respond_to?(:set_unique_id)
157
+ result = database.save_doc(self, bulk)
158
+ (result["ok"] == true) ? self : false
159
+ end
160
+
161
+ # Creates the document in the db. Raises an exception
162
+ # if the document is not created properly.
163
+ def create!
164
+ raise "#{self.inspect} failed to save" unless self.create
165
+ end
166
+
167
+ # Trigger the callbacks (before, after, around)
168
+ # only if the document isn't new
169
+ def update(bulk = false)
170
+ caught = catch(:halt) do
171
+ if self.new_document?
172
+ save(bulk)
173
+ else
174
+ _run_update_callbacks do
175
+ _run_save_callbacks do
176
+ save_without_callbacks(bulk)
177
+ end
178
+ end
179
+ end
180
+ end
181
+ end
182
+
183
+ # Trigger the callbacks (before, after, around)
184
+ # and save the document
185
+ def save(bulk = false)
186
+ caught = catch(:halt) do
187
+ if self.new_document?
188
+ _run_save_callbacks do
189
+ save_without_callbacks(bulk)
190
+ end
191
+ else
192
+ update(bulk)
193
+ end
194
+ end
195
+ end
196
+
197
+ # Overridden to set the unique ID.
198
+ # Returns a boolean value
199
+ def save_without_callbacks(bulk = false)
200
+ raise ArgumentError, "a document requires a database to be saved to (The document or the #{self.class} default database were not set)" unless database
201
+ set_unique_id if new_document? && self.respond_to?(:set_unique_id)
202
+ result = database.save_doc(self, bulk)
203
+ result["ok"] == true
204
+ end
205
+
206
+ # Saves the document to the db using save. Raises an exception
207
+ # if the document is not saved properly.
208
+ def save!
209
+ raise "#{self.inspect} failed to save" unless self.save
210
+ end
211
+
212
+ # Deletes the document from the database. Runs the :destroy callbacks.
213
+ # Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
214
+ # document to be saved to a new <tt>_id</tt>.
215
+ def destroy(bulk=false)
216
+ caught = catch(:halt) do
217
+ _run_destroy_callbacks do
218
+ result = database.delete_doc(self, bulk)
219
+ if result['ok']
220
+ self.delete('_rev')
221
+ self.delete('_id')
222
+ end
223
+ result['ok']
224
+ end
225
+ end
226
+ end
227
+
228
+ end
229
+ end