samlown-couchrest 0.35

Sign up to get free protection for your applications and to get access to all the features.
Files changed (105) hide show
  1. data/LICENSE +176 -0
  2. data/README.md +46 -0
  3. data/Rakefile +67 -0
  4. data/THANKS.md +19 -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 +114 -0
  17. data/lib/couchrest/commands/generate.rb +71 -0
  18. data/lib/couchrest/commands/push.rb +103 -0
  19. data/lib/couchrest/core/adapters/restclient.rb +35 -0
  20. data/lib/couchrest/core/database.rb +377 -0
  21. data/lib/couchrest/core/design.rb +79 -0
  22. data/lib/couchrest/core/document.rb +84 -0
  23. data/lib/couchrest/core/http_abstraction.rb +48 -0
  24. data/lib/couchrest/core/response.rb +16 -0
  25. data/lib/couchrest/core/rest_api.rb +49 -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 +51 -0
  30. data/lib/couchrest/helper/upgrade.rb +51 -0
  31. data/lib/couchrest/middlewares/logger.rb +263 -0
  32. data/lib/couchrest/mixins/attachments.rb +31 -0
  33. data/lib/couchrest/mixins/attribute_protection.rb +74 -0
  34. data/lib/couchrest/mixins/callbacks.rb +532 -0
  35. data/lib/couchrest/mixins/class_proxy.rb +124 -0
  36. data/lib/couchrest/mixins/collection.rb +260 -0
  37. data/lib/couchrest/mixins/design_doc.rb +103 -0
  38. data/lib/couchrest/mixins/document_queries.rb +80 -0
  39. data/lib/couchrest/mixins/extended_attachments.rb +70 -0
  40. data/lib/couchrest/mixins/extended_document_mixins.rb +9 -0
  41. data/lib/couchrest/mixins/properties.rb +154 -0
  42. data/lib/couchrest/mixins/validation.rb +246 -0
  43. data/lib/couchrest/mixins/views.rb +173 -0
  44. data/lib/couchrest/mixins.rb +4 -0
  45. data/lib/couchrest/monkeypatches.rb +113 -0
  46. data/lib/couchrest/more/casted_model.rb +58 -0
  47. data/lib/couchrest/more/extended_document.rb +310 -0
  48. data/lib/couchrest/more/property.rb +50 -0
  49. data/lib/couchrest/more/typecast.rb +175 -0
  50. data/lib/couchrest/support/blank.rb +42 -0
  51. data/lib/couchrest/support/class.rb +190 -0
  52. data/lib/couchrest/support/rails.rb +42 -0
  53. data/lib/couchrest/validation/auto_validate.rb +157 -0
  54. data/lib/couchrest/validation/contextual_validators.rb +78 -0
  55. data/lib/couchrest/validation/validation_errors.rb +125 -0
  56. data/lib/couchrest/validation/validators/absent_field_validator.rb +74 -0
  57. data/lib/couchrest/validation/validators/confirmation_validator.rb +107 -0
  58. data/lib/couchrest/validation/validators/format_validator.rb +122 -0
  59. data/lib/couchrest/validation/validators/formats/email.rb +66 -0
  60. data/lib/couchrest/validation/validators/formats/url.rb +43 -0
  61. data/lib/couchrest/validation/validators/generic_validator.rb +120 -0
  62. data/lib/couchrest/validation/validators/length_validator.rb +139 -0
  63. data/lib/couchrest/validation/validators/method_validator.rb +89 -0
  64. data/lib/couchrest/validation/validators/numeric_validator.rb +109 -0
  65. data/lib/couchrest/validation/validators/required_field_validator.rb +114 -0
  66. data/lib/couchrest.rb +162 -0
  67. data/spec/couchrest/core/couchrest_spec.rb +184 -0
  68. data/spec/couchrest/core/database_spec.rb +840 -0
  69. data/spec/couchrest/core/design_spec.rb +138 -0
  70. data/spec/couchrest/core/document_spec.rb +275 -0
  71. data/spec/couchrest/core/server_spec.rb +35 -0
  72. data/spec/couchrest/helpers/pager_spec.rb +122 -0
  73. data/spec/couchrest/helpers/streamer_spec.rb +52 -0
  74. data/spec/couchrest/more/attribute_protection_spec.rb +150 -0
  75. data/spec/couchrest/more/casted_extended_doc_spec.rb +79 -0
  76. data/spec/couchrest/more/casted_model_spec.rb +406 -0
  77. data/spec/couchrest/more/extended_doc_attachment_spec.rb +135 -0
  78. data/spec/couchrest/more/extended_doc_inherited_spec.rb +40 -0
  79. data/spec/couchrest/more/extended_doc_spec.rb +797 -0
  80. data/spec/couchrest/more/extended_doc_subclass_spec.rb +98 -0
  81. data/spec/couchrest/more/extended_doc_view_spec.rb +456 -0
  82. data/spec/couchrest/more/property_spec.rb +628 -0
  83. data/spec/fixtures/attachments/README +3 -0
  84. data/spec/fixtures/attachments/couchdb.png +0 -0
  85. data/spec/fixtures/attachments/test.html +11 -0
  86. data/spec/fixtures/more/article.rb +35 -0
  87. data/spec/fixtures/more/card.rb +22 -0
  88. data/spec/fixtures/more/cat.rb +20 -0
  89. data/spec/fixtures/more/course.rb +22 -0
  90. data/spec/fixtures/more/event.rb +8 -0
  91. data/spec/fixtures/more/invoice.rb +17 -0
  92. data/spec/fixtures/more/person.rb +9 -0
  93. data/spec/fixtures/more/question.rb +6 -0
  94. data/spec/fixtures/more/service.rb +12 -0
  95. data/spec/fixtures/more/user.rb +22 -0
  96. data/spec/fixtures/views/lib.js +3 -0
  97. data/spec/fixtures/views/test_view/lib.js +3 -0
  98. data/spec/fixtures/views/test_view/only-map.js +4 -0
  99. data/spec/fixtures/views/test_view/test-map.js +3 -0
  100. data/spec/fixtures/views/test_view/test-reduce.js +3 -0
  101. data/spec/spec.opts +6 -0
  102. data/spec/spec_helper.rb +49 -0
  103. data/utils/remap.rb +27 -0
  104. data/utils/subset.rb +30 -0
  105. metadata +223 -0
@@ -0,0 +1,246 @@
1
+ # Extracted from dm-validations 0.9.10
2
+ #
3
+ # Copyright (c) 2007 Guy van den Berg
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining
6
+ # a copy of this software and associated documentation files (the
7
+ # "Software"), to deal in the Software without restriction, including
8
+ # without limitation the rights to use, copy, modify, merge, publish,
9
+ # distribute, sublicense, and/or sell copies of the Software, and to
10
+ # permit persons to whom the Software is furnished to do so, subject to
11
+ # the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be
14
+ # included in all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ class Object
25
+ def validatable?
26
+ false
27
+ end
28
+ end
29
+
30
+ require 'pathname'
31
+ require File.join(File.dirname(__FILE__), '..', 'support', 'class')
32
+
33
+ dir = File.join(Pathname(__FILE__).dirname.expand_path, '..', 'validation')
34
+
35
+ require File.join(dir, 'validation_errors')
36
+ require File.join(dir, 'contextual_validators')
37
+ require File.join(dir, 'auto_validate')
38
+
39
+ require File.join(dir, 'validators', 'generic_validator')
40
+ require File.join(dir, 'validators', 'required_field_validator')
41
+ require File.join(dir, 'validators', 'absent_field_validator')
42
+ require File.join(dir, 'validators', 'format_validator')
43
+ require File.join(dir, 'validators', 'length_validator')
44
+ require File.join(dir, 'validators', 'numeric_validator')
45
+ require File.join(dir, 'validators', 'method_validator')
46
+ require File.join(dir, 'validators', 'confirmation_validator')
47
+
48
+ module CouchRest
49
+ module Validation
50
+
51
+ def self.included(base)
52
+ base.extlib_inheritable_accessor(:auto_validation)
53
+ base.class_eval <<-EOS, __FILE__, __LINE__ + 1
54
+ # Callbacks
55
+ define_callbacks :validate
56
+
57
+ # Turn off auto validation by default
58
+ self.auto_validation ||= false
59
+
60
+ # Force the auto validation for the class properties
61
+ # This feature is still not fully ported over,
62
+ # test are lacking, so please use with caution
63
+ def self.auto_validate!
64
+ self.auto_validation = true
65
+ end
66
+
67
+ # share the validations with subclasses
68
+ def self.inherited(subklass)
69
+ self.validators.contexts.each do |k, v|
70
+ subklass.validators.contexts[k] = v.dup
71
+ end
72
+ super
73
+ end
74
+ EOS
75
+
76
+ base.extend(ClassMethods)
77
+ base.class_eval <<-EOS, __FILE__, __LINE__ + 1
78
+ define_callbacks :validate
79
+ if method_defined?(:_run_save_callbacks)
80
+ set_callback :save, :before, :check_validations
81
+ end
82
+ EOS
83
+ base.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
84
+ def self.define_property(name, options={})
85
+ super
86
+ auto_generate_validations(properties.last) if properties && properties.size > 0
87
+ autovalidation_check = true
88
+ end
89
+ RUBY_EVAL
90
+ end
91
+
92
+ # Ensures the object is valid for the context provided, and otherwise
93
+ # throws :halt and returns false.
94
+ #
95
+ def check_validations(context = :default)
96
+ throw(:halt, false) unless context.nil? || valid?(context)
97
+ end
98
+
99
+ # Return the ValidationErrors
100
+ #
101
+ def errors
102
+ @errors ||= ValidationErrors.new
103
+ end
104
+
105
+ # Mark this resource as validatable. When we validate associations of a
106
+ # resource we can check if they respond to validatable? before trying to
107
+ # recursivly validate them
108
+ #
109
+ def validatable?
110
+ true
111
+ end
112
+
113
+ # Alias for valid?(:default)
114
+ #
115
+ def valid_for_default?
116
+ valid?(:default)
117
+ end
118
+
119
+ # Check if a resource is valid in a given context
120
+ #
121
+ def valid?(context = :default)
122
+ recursive_valid?(self, context, true)
123
+ end
124
+
125
+ # checking on casted objects
126
+ def validate_casted_arrays
127
+ result = true
128
+ array_casted_properties = self.class.properties.select { |property| property.casted && property.type.instance_of?(Array) }
129
+ array_casted_properties.each do |property|
130
+ casted_values = self.send(property.name)
131
+ next unless casted_values.is_a?(Array) && casted_values.first.respond_to?(:valid?)
132
+ casted_values.each do |value|
133
+ result = (result && value.valid?) if value.respond_to?(:valid?)
134
+ end
135
+ end
136
+ result
137
+ end
138
+
139
+ # Do recursive validity checking
140
+ #
141
+ def recursive_valid?(target, context, state)
142
+ valid = state
143
+ target.each do |key, prop|
144
+ if prop.is_a?(Array)
145
+ prop.each do |item|
146
+ if item.validatable?
147
+ valid = recursive_valid?(item, context, valid) && valid
148
+ end
149
+ end
150
+ elsif prop.validatable?
151
+ valid = recursive_valid?(prop, context, valid) && valid
152
+ end
153
+ end
154
+ target._run_validate_callbacks do
155
+ target.class.validators.execute(context, target) && valid
156
+ end
157
+ end
158
+
159
+
160
+ def validation_property_value(name)
161
+ self.respond_to?(name, true) ? self.send(name) : nil
162
+ end
163
+
164
+ # Get the corresponding Object property, if it exists.
165
+ def validation_property(field_name)
166
+ properties.find{|p| p.name == field_name}
167
+ end
168
+
169
+ module ClassMethods
170
+ include CouchRest::Validation::ValidatesPresent
171
+ include CouchRest::Validation::ValidatesAbsent
172
+ include CouchRest::Validation::ValidatesIsConfirmed
173
+ # include CouchRest::Validation::ValidatesIsPrimitive
174
+ # include CouchRest::Validation::ValidatesIsAccepted
175
+ include CouchRest::Validation::ValidatesFormat
176
+ include CouchRest::Validation::ValidatesLength
177
+ # include CouchRest::Validation::ValidatesWithin
178
+ include CouchRest::Validation::ValidatesIsNumber
179
+ include CouchRest::Validation::ValidatesWithMethod
180
+ # include CouchRest::Validation::ValidatesWithBlock
181
+ # include CouchRest::Validation::ValidatesIsUnique
182
+ include CouchRest::Validation::AutoValidate
183
+
184
+ # Return the set of contextual validators or create a new one
185
+ #
186
+ def validators
187
+ @validations ||= ContextualValidators.new
188
+ end
189
+
190
+ # Clean up the argument list and return a opts hash, including the
191
+ # merging of any default opts. Set the context to default if none is
192
+ # provided. Also allow :context to be aliased to :on, :when & group
193
+ #
194
+ def opts_from_validator_args(args, defaults = nil)
195
+ opts = args.last.kind_of?(Hash) ? args.pop : {}
196
+ context = :default
197
+ context = opts[:context] if opts.has_key?(:context)
198
+ context = opts.delete(:on) if opts.has_key?(:on)
199
+ context = opts.delete(:when) if opts.has_key?(:when)
200
+ context = opts.delete(:group) if opts.has_key?(:group)
201
+ opts[:context] = context
202
+ opts.merge!(defaults) unless defaults.nil?
203
+ opts
204
+ end
205
+
206
+ # Given a new context create an instance method of
207
+ # valid_for_<context>? which simply calls valid?(context)
208
+ # if it does not already exist
209
+ #
210
+ def create_context_instance_methods(context)
211
+ name = "valid_for_#{context.to_s}?" # valid_for_signup?
212
+ if !self.instance_methods.include?(name)
213
+ class_eval <<-EOS, __FILE__, __LINE__ + 1
214
+ def #{name} # def valid_for_signup?
215
+ valid?('#{context.to_s}'.to_sym) # valid?('signup'.to_sym)
216
+ end # end
217
+ EOS
218
+ end
219
+ end
220
+
221
+ # Create a new validator of the given klazz and push it onto the
222
+ # requested context for each of the attributes in the fields list
223
+ #
224
+ def add_validator_to_context(opts, fields, klazz)
225
+ fields.each do |field|
226
+ validator = klazz.new(field.to_sym, opts)
227
+ if opts[:context].is_a?(Symbol)
228
+ unless validators.context(opts[:context]).include?(validator)
229
+ validators.context(opts[:context]) << validator
230
+ create_context_instance_methods(opts[:context])
231
+ end
232
+ elsif opts[:context].is_a?(Array)
233
+ opts[:context].each do |c|
234
+ unless validators.context(c).include?(validator)
235
+ validators.context(c) << validator
236
+ create_context_instance_methods(c)
237
+ end
238
+ end
239
+ end
240
+ end
241
+ end
242
+
243
+ end # module ClassMethods
244
+ end # module Validation
245
+
246
+ end # module CouchRest
@@ -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|create_from_database(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|create_from_database(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,4 @@
1
+ mixins_dir = File.join(File.dirname(__FILE__), 'mixins')
2
+
3
+ require File.join(mixins_dir, 'attachments')
4
+ require File.join(mixins_dir, 'callbacks')
@@ -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, "IO timeout"
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,58 @@
1
+ require File.expand_path('../../mixins/properties', __FILE__)
2
+
3
+
4
+ module CouchRest
5
+ module CastedModel
6
+
7
+ def self.included(base)
8
+ base.send(:include, ::CouchRest::Callbacks)
9
+ base.send(:include, ::CouchRest::Mixins::Properties)
10
+ base.send(:attr_accessor, :casted_by)
11
+ base.send(:attr_accessor, :document_saved)
12
+ end
13
+
14
+ def initialize(keys={})
15
+ raise StandardError unless self.is_a? Hash
16
+ apply_defaults # defined in CouchRest::Mixins::Properties
17
+ super()
18
+ keys.each do |k,v|
19
+ self[k.to_s] = v
20
+ end if keys
21
+ cast_keys # defined in CouchRest::Mixins::Properties
22
+ end
23
+
24
+ def []= key, value
25
+ super(key.to_s, value)
26
+ end
27
+
28
+ def [] key
29
+ super(key.to_s)
30
+ end
31
+
32
+ # Gets a reference to the top level extended
33
+ # document that a model is saved inside of
34
+ def base_doc
35
+ return nil unless @casted_by
36
+ @casted_by.base_doc
37
+ end
38
+
39
+ # False if the casted model has already
40
+ # been saved in the containing document
41
+ def new?
42
+ !@document_saved
43
+ end
44
+ alias :new_record? :new?
45
+
46
+ # Sets the attributes from a hash
47
+ def update_attributes_without_saving(hash)
48
+ hash.each do |k, v|
49
+ raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=")
50
+ end
51
+ hash.each do |k, v|
52
+ self.send("#{k}=",v)
53
+ end
54
+ end
55
+ alias :attributes= :update_attributes_without_saving
56
+
57
+ end
58
+ end