sporkd-couchrest 0.30

Sign up to get free protection for your applications and to get access to all the features.
Files changed (96) hide show
  1. data/LICENSE +176 -0
  2. data/README.md +176 -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 +33 -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 +317 -0
  20. data/lib/couchrest/core/design.rb +79 -0
  21. data/lib/couchrest/core/document.rb +84 -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/attachments.rb +31 -0
  29. data/lib/couchrest/mixins/callbacks.rb +532 -0
  30. data/lib/couchrest/mixins/class_proxy.rb +112 -0
  31. data/lib/couchrest/mixins/collection.rb +222 -0
  32. data/lib/couchrest/mixins/design_doc.rb +98 -0
  33. data/lib/couchrest/mixins/document_queries.rb +51 -0
  34. data/lib/couchrest/mixins/extended_attachments.rb +74 -0
  35. data/lib/couchrest/mixins/extended_document_mixins.rb +8 -0
  36. data/lib/couchrest/mixins/properties.rb +181 -0
  37. data/lib/couchrest/mixins/validation.rb +246 -0
  38. data/lib/couchrest/mixins/views.rb +173 -0
  39. data/lib/couchrest/mixins.rb +4 -0
  40. data/lib/couchrest/monkeypatches.rb +113 -0
  41. data/lib/couchrest/more/casted_model.rb +57 -0
  42. data/lib/couchrest/more/extended_document.rb +283 -0
  43. data/lib/couchrest/more/property.rb +59 -0
  44. data/lib/couchrest/support/blank.rb +42 -0
  45. data/lib/couchrest/support/class.rb +190 -0
  46. data/lib/couchrest/support/rails.rb +47 -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/lib/couchrest.rb +200 -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 +73 -0
  69. data/spec/couchrest/more/casted_model_spec.rb +406 -0
  70. data/spec/couchrest/more/extended_doc_attachment_spec.rb +135 -0
  71. data/spec/couchrest/more/extended_doc_spec.rb +712 -0
  72. data/spec/couchrest/more/extended_doc_subclass_spec.rb +98 -0
  73. data/spec/couchrest/more/extended_doc_view_spec.rb +415 -0
  74. data/spec/couchrest/more/property_spec.rb +233 -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 +19 -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 +9 -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,222 @@
1
+ module CouchRest
2
+ module Mixins
3
+ module Collection
4
+
5
+ def self.included(base)
6
+ base.extend(ClassMethods)
7
+ end
8
+
9
+ module ClassMethods
10
+
11
+ # Creates a new class method, find_all_<collection_name>, that will
12
+ # execute the view specified with the design_doc and view_name
13
+ # parameters, along with the specified view_options. This method will
14
+ # return the results of the view as an Array of objects which are
15
+ # instances of the class.
16
+ #
17
+ # This method is handy for objects that do not use the view_by method
18
+ # to declare their views.
19
+ def provides_collection(collection_name, design_doc, view_name, view_options)
20
+ class_eval <<-END, __FILE__, __LINE__ + 1
21
+ def self.find_all_#{collection_name}(options = {})
22
+ view_options = #{view_options.inspect} || {}
23
+ CollectionProxy.new(@database, "#{design_doc}", "#{view_name}", view_options.merge(options), Kernel.const_get('#{self}'))
24
+ end
25
+ END
26
+ end
27
+
28
+ # Fetch a group of objects from CouchDB. Options can include:
29
+ # :page - Specifies the page to load (starting at 1)
30
+ # :per_page - Specifies the number of objects to load per page
31
+ #
32
+ # Defaults are used if these options are not specified.
33
+ def paginate(options)
34
+ proxy = create_collection_proxy(options)
35
+ proxy.paginate(options)
36
+ end
37
+
38
+ # Iterate over the objects in a collection, fetching them from CouchDB
39
+ # in groups. Options can include:
40
+ # :page - Specifies the page to load
41
+ # :per_page - Specifies the number of objects to load per page
42
+ #
43
+ # Defaults are used if these options are not specified.
44
+ def paginated_each(options, &block)
45
+ proxy = create_collection_proxy(options)
46
+ proxy.paginated_each(options, &block)
47
+ end
48
+
49
+ # Create a CollectionProxy for the specified view and options.
50
+ # CollectionProxy behaves just like an Array, but offers support for
51
+ # pagination.
52
+ def collection_proxy_for(design_doc, view_name, view_options = {})
53
+ options = view_options.merge(:design_doc => design_doc, :view_name => view_name)
54
+ create_collection_proxy(options)
55
+ end
56
+
57
+ private
58
+
59
+ def create_collection_proxy(options)
60
+ design_doc, view_name, view_options = parse_view_options(options)
61
+ CollectionProxy.new(@database, design_doc, view_name, view_options, self)
62
+ end
63
+
64
+ def parse_view_options(options)
65
+ design_doc = options.delete(:design_doc)
66
+ raise ArgumentError, 'design_doc is required' if design_doc.nil?
67
+
68
+ view_name = options.delete(:view_name)
69
+ raise ArgumentError, 'view_name is required' if view_name.nil?
70
+
71
+ default_view_options = (design_doc.class == Design &&
72
+ design_doc['views'][view_name.to_s] &&
73
+ design_doc['views'][view_name.to_s]["couchrest-defaults"]) || {}
74
+ view_options = default_view_options.merge(options)
75
+
76
+ [design_doc, view_name, view_options]
77
+ end
78
+ end
79
+
80
+ class CollectionProxy
81
+ alias_method :proxy_respond_to?, :respond_to?
82
+ instance_methods.each { |m| undef_method m unless m =~ /(^__|^nil\?$|^send$|proxy_|^object_id$)/ }
83
+
84
+ DEFAULT_PAGE = 1
85
+ DEFAULT_PER_PAGE = 30
86
+
87
+ # Create a new CollectionProxy to represent the specified view. If a
88
+ # container class is specified, the proxy will create an object of the
89
+ # given type for each row that comes back from the view. If no
90
+ # container class is specified, the raw results are returned.
91
+ #
92
+ # The CollectionProxy provides support for paginating over a collection
93
+ # via the paginate, and paginated_each methods.
94
+ def initialize(database, design_doc, view_name, view_options = {}, container_class = nil)
95
+ raise ArgumentError, "database is a required parameter" if database.nil?
96
+
97
+ @database = database
98
+ @container_class = container_class
99
+
100
+ strip_pagination_options(view_options)
101
+ @view_options = view_options
102
+
103
+ if design_doc.class == Design
104
+ @view_name = "#{design_doc.name}/#{view_name}"
105
+ else
106
+ @view_name = "#{design_doc}/#{view_name}"
107
+ end
108
+ end
109
+
110
+ # See Collection.paginate
111
+ def paginate(options = {})
112
+ page, per_page = parse_options(options)
113
+ results = @database.view(@view_name, pagination_options(page, per_page))
114
+ remember_where_we_left_off(results, page)
115
+ convert_to_container_array(results)
116
+ end
117
+
118
+ # See Collection.paginated_each
119
+ def paginated_each(options = {}, &block)
120
+ page, per_page = parse_options(options)
121
+
122
+ begin
123
+ collection = paginate({:page => page, :per_page => per_page})
124
+ collection.each(&block)
125
+ page += 1
126
+ end until collection.size < per_page
127
+ end
128
+
129
+ def respond_to?(*args)
130
+ proxy_respond_to?(*args) || (load_target && @target.respond_to?(*args))
131
+ end
132
+
133
+ # Explicitly proxy === because the instance method removal above
134
+ # doesn't catch it.
135
+ def ===(other)
136
+ load_target
137
+ other === @target
138
+ end
139
+
140
+ private
141
+
142
+ def method_missing(method, *args)
143
+ if load_target
144
+ if block_given?
145
+ @target.send(method, *args) { |*block_args| yield(*block_args) }
146
+ else
147
+ @target.send(method, *args)
148
+ end
149
+ end
150
+ end
151
+
152
+ def load_target
153
+ unless loaded?
154
+ results = @database.view(@view_name, @view_options)
155
+ @target = convert_to_container_array(results)
156
+ end
157
+ @loaded = true
158
+ @target
159
+ end
160
+
161
+ def loaded?
162
+ @loaded
163
+ end
164
+
165
+ def reload
166
+ reset
167
+ load_target
168
+ self unless @target.nil?
169
+ end
170
+
171
+ def reset
172
+ @loaded = false
173
+ @target = nil
174
+ end
175
+
176
+ def inspect
177
+ load_target
178
+ @target.inspect
179
+ end
180
+
181
+ def convert_to_container_array(results)
182
+ if @container_class.nil?
183
+ results
184
+ else
185
+ results['rows'].collect { |row| @container_class.new(row['doc']) } unless results['rows'].nil?
186
+ end
187
+ end
188
+
189
+ def pagination_options(page, per_page)
190
+ view_options = @view_options.clone
191
+ if @last_key && @last_docid && @last_page == page - 1
192
+ view_options.delete(:key)
193
+ options = { :startkey => @last_key, :startkey_docid => @last_docid, :limit => per_page, :skip => 1 }
194
+ else
195
+ options = { :limit => per_page, :skip => per_page * (page - 1) }
196
+ end
197
+ view_options.merge(options)
198
+ end
199
+
200
+ def parse_options(options)
201
+ page = options.delete(:page) || DEFAULT_PAGE
202
+ per_page = options.delete(:per_page) || DEFAULT_PER_PAGE
203
+ [page.to_i, per_page.to_i]
204
+ end
205
+
206
+ def strip_pagination_options(options)
207
+ parse_options(options)
208
+ end
209
+
210
+ def remember_where_we_left_off(results, page)
211
+ last_row = results['rows'].last
212
+ if last_row
213
+ @last_key = last_row['key']
214
+ @last_docid = last_row['id']
215
+ end
216
+ @last_page = page
217
+ end
218
+ end
219
+
220
+ end
221
+ end
222
+ end
@@ -0,0 +1,98 @@
1
+ require 'digest/md5'
2
+
3
+ module CouchRest
4
+ module Mixins
5
+ module DesignDoc
6
+
7
+ def self.included(base)
8
+ base.extend(ClassMethods)
9
+ end
10
+
11
+ module ClassMethods
12
+ attr_accessor :design_doc, :design_doc_slug_cache, :design_doc_fresh
13
+
14
+ def design_doc
15
+ @design_doc ||= Design.new(default_design_doc)
16
+ end
17
+
18
+ def design_doc_id
19
+ "_design/#{design_doc_slug}"
20
+ end
21
+
22
+ def design_doc_slug
23
+ return design_doc_slug_cache if (design_doc_slug_cache && design_doc_fresh)
24
+ funcs = []
25
+ design_doc['views'].each do |name, view|
26
+ funcs << "#{name}/#{view['map']}#{view['reduce']}"
27
+ end
28
+ self.design_doc_slug_cache = self.to_s
29
+ end
30
+
31
+ def default_design_doc
32
+ {
33
+ "language" => "javascript",
34
+ "views" => {
35
+ 'all' => {
36
+ 'map' => "function(doc) {
37
+ if (doc['couchrest-type'] == '#{self.to_s}') {
38
+ emit(null,1);
39
+ }
40
+ }"
41
+ }
42
+ }
43
+ }
44
+ end
45
+
46
+ def refresh_design_doc
47
+ reset_design_doc
48
+ save_design_doc
49
+ end
50
+
51
+ # Save the design doc onto the default database, and update the
52
+ # design_doc attribute
53
+ def save_design_doc
54
+ reset_design_doc unless design_doc_fresh
55
+ self.design_doc = update_design_doc(design_doc)
56
+ end
57
+
58
+ # Save the design doc onto a target database in a thread-safe way,
59
+ # not modifying the model's design_doc
60
+ def save_design_doc_on(db)
61
+ update_design_doc(Design.new(design_doc), db)
62
+ end
63
+
64
+ private
65
+
66
+ def reset_design_doc
67
+ current = self.database.get(design_doc_id) rescue nil
68
+ design_doc['_id'] = design_doc_id
69
+ if current.nil?
70
+ design_doc.delete('_rev')
71
+ else
72
+ design_doc['_rev'] = current['_rev']
73
+ end
74
+ self.design_doc_fresh = true
75
+ end
76
+
77
+ # Writes out a design_doc to a given database, returning the
78
+ # updated design doc
79
+ def update_design_doc(design_doc, db = database)
80
+ saved = db.get(design_doc['_id']) rescue nil
81
+ if saved
82
+ design_doc['views'].each do |name, view|
83
+ saved['views'][name] = view
84
+ end
85
+ db.save_doc(saved)
86
+ saved
87
+ else
88
+ design_doc.database = db
89
+ design_doc.save
90
+ design_doc
91
+ end
92
+ end
93
+
94
+ end # module ClassMethods
95
+
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,51 @@
1
+ module CouchRest
2
+ module Mixins
3
+ module DocumentQueries
4
+
5
+ def self.included(base)
6
+ base.extend(ClassMethods)
7
+ end
8
+
9
+ module ClassMethods
10
+
11
+ # Load all documents that have the "couchrest-type" field equal to the
12
+ # name of the current class. Take the standard set of
13
+ # CouchRest::Database#view options.
14
+ def all(opts = {}, &block)
15
+ view(:all, {:reduce => false}.merge(opts), &block)
16
+ end
17
+
18
+ # Returns the number of documents that have the "couchrest-type" field
19
+ # equal to the name of the current class. Takes the standard set of
20
+ # CouchRest::Database#view options
21
+ def count(opts = {}, &block)
22
+ all({:raw => true, :limit => 0}.merge(opts), &block)['total_rows']
23
+ end
24
+
25
+ # Load the first document that have the "couchrest-type" field equal to
26
+ # the name of the current class.
27
+ #
28
+ # ==== Returns
29
+ # Object:: The first object instance available
30
+ # or
31
+ # Nil:: if no instances available
32
+ #
33
+ # ==== Parameters
34
+ # opts<Hash>::
35
+ # View options, see <tt>CouchRest::Database#view</tt> options for more info.
36
+ def first(opts = {})
37
+ first_instance = self.all(opts.merge!(:limit => 1))
38
+ first_instance.empty? ? nil : first_instance.first
39
+ end
40
+
41
+ # Load a document from the database by id
42
+ def get(id, db = database)
43
+ doc = db.get id
44
+ new(doc)
45
+ end
46
+
47
+ end
48
+
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,74 @@
1
+ module CouchRest
2
+ module Mixins
3
+ module ExtendedAttachments
4
+
5
+ # creates a file attachment to the current doc
6
+ def create_attachment(args={})
7
+ raise ArgumentError unless args[:file] && args[:name]
8
+ return if has_attachment?(args[:name])
9
+ self['_attachments'] ||= {}
10
+ set_attachment_attr(args)
11
+ rescue ArgumentError => e
12
+ raise ArgumentError, 'You must specify :file and :name'
13
+ end
14
+
15
+ # reads the data from an attachment
16
+ def read_attachment(attachment_name)
17
+ Base64.decode64(database.fetch_attachment(self, attachment_name))
18
+ end
19
+
20
+ # modifies a file attachment on the current doc
21
+ def update_attachment(args={})
22
+ raise ArgumentError unless args[:file] && args[:name]
23
+ return unless has_attachment?(args[:name])
24
+ delete_attachment(args[:name])
25
+ set_attachment_attr(args)
26
+ rescue ArgumentError => e
27
+ raise ArgumentError, 'You must specify :file and :name'
28
+ end
29
+
30
+ # deletes a file attachment from the current doc
31
+ def delete_attachment(attachment_name)
32
+ return unless self['_attachments']
33
+ self['_attachments'].delete attachment_name
34
+ end
35
+
36
+ # returns true if attachment_name exists
37
+ def has_attachment?(attachment_name)
38
+ !!(self['_attachments'] && self['_attachments'][attachment_name] && !self['_attachments'][attachment_name].empty?)
39
+ end
40
+
41
+ # returns URL to fetch the attachment from
42
+ def attachment_url(attachment_name)
43
+ return unless has_attachment?(attachment_name)
44
+ "#{database.root}/#{self.id}/#{attachment_name}"
45
+ end
46
+
47
+ # returns URI to fetch the attachment from
48
+ def attachment_uri(attachment_name)
49
+ return unless has_attachment?(attachment_name)
50
+ "#{database.uri}/#{self.id}/#{attachment_name}"
51
+ end
52
+
53
+ private
54
+
55
+ def encode_attachment(data)
56
+ ::Base64.encode64(data).gsub(/\r|\n/,'')
57
+ end
58
+
59
+ def get_mime_type(file)
60
+ ::MIME::Types.type_for(file.path).empty? ?
61
+ 'text\/plain' : MIME::Types.type_for(file.path).first.content_type.gsub(/\//,'\/')
62
+ end
63
+
64
+ def set_attachment_attr(args)
65
+ content_type = args[:content_type] ? args[:content_type] : get_mime_type(args[:file])
66
+ self['_attachments'][args[:name]] = {
67
+ 'content-type' => content_type,
68
+ 'data' => encode_attachment(args[:file].read)
69
+ }
70
+ end
71
+
72
+ end # module ExtendedAttachments
73
+ end
74
+ end
@@ -0,0 +1,8 @@
1
+ require File.join(File.dirname(__FILE__), 'properties')
2
+ require File.join(File.dirname(__FILE__), 'document_queries')
3
+ require File.join(File.dirname(__FILE__), 'views')
4
+ require File.join(File.dirname(__FILE__), 'design_doc')
5
+ require File.join(File.dirname(__FILE__), 'validation')
6
+ require File.join(File.dirname(__FILE__), 'extended_attachments')
7
+ require File.join(File.dirname(__FILE__), 'class_proxy')
8
+ require File.join(File.dirname(__FILE__), 'collection')
@@ -0,0 +1,181 @@
1
+ require 'time'
2
+ require File.join(File.dirname(__FILE__), '..', 'more', 'property')
3
+
4
+ class Time
5
+ # returns a local time value much faster than Time.parse
6
+ def self.mktime_with_offset(string)
7
+ string =~ /(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2}) ([\+\-])(\d{2})/
8
+ # $1 = year
9
+ # $2 = month
10
+ # $3 = day
11
+ # $4 = hours
12
+ # $5 = minutes
13
+ # $6 = seconds
14
+ # $7 = time zone direction
15
+ # $8 = tz difference
16
+ # utc time with wrong TZ info:
17
+ time = mktime($1, RFC2822_MONTH_NAME[$2.to_i - 1], $3, $4, $5, $6, $7)
18
+ tz_difference = ("#{$7 == '-' ? '+' : '-'}#{$8}".to_i * 3600)
19
+ time + tz_difference + zone_offset(time.zone)
20
+ end
21
+ end
22
+
23
+ module CouchRest
24
+ module Mixins
25
+ module Properties
26
+
27
+ class IncludeError < StandardError; end
28
+
29
+ def self.included(base)
30
+ base.class_eval <<-EOS, __FILE__, __LINE__
31
+ extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
32
+ self.properties ||= []
33
+ EOS
34
+ base.extend(ClassMethods)
35
+ raise CouchRest::Mixins::Properties::IncludeError, "You can only mixin Properties in a class responding to [] and []=, if you tried to mixin CastedModel, make sure your class inherits from Hash or responds to the proper methods" unless (base.new.respond_to?(:[]) && base.new.respond_to?(:[]=))
36
+ end
37
+
38
+ def apply_defaults
39
+ return if self.respond_to?(:new?) && (new? == false)
40
+ return unless self.class.respond_to?(:properties)
41
+ return if self.class.properties.empty?
42
+ # TODO: cache the default object
43
+ self.class.properties.each do |property|
44
+ key = property.name.to_s
45
+ # let's make sure we have a default
46
+ unless property.default.nil?
47
+ if property.default.class == Proc
48
+ self[key] = property.default.call
49
+ else
50
+ self[key] = Marshal.load(Marshal.dump(property.default))
51
+ end
52
+ end
53
+ end
54
+ end
55
+
56
+ def cast_keys
57
+ return unless self.class.properties
58
+ self.class.properties.each do |property|
59
+ cast_property(property)
60
+ end
61
+ end
62
+
63
+ def cast_property(property, assigned=false)
64
+ return unless property.casted
65
+ key = self.has_key?(property.name) ? property.name : property.name.to_sym
66
+ # Don't cast the property unless it has a value
67
+ return unless self[key]
68
+ target = property.type
69
+ if target.is_a?(Array)
70
+ klass = ::CouchRest.constantize(target[0])
71
+ arr = self[key].dup.collect do |value|
72
+ unless value.instance_of?(klass)
73
+ value = convert_property_value(property, klass, value)
74
+ end
75
+ associate_casted_to_parent(value, assigned)
76
+ value
77
+ end
78
+ self[key] = klass != String ? CastedArray.new(arr) : arr
79
+ self[key].casted_by = self if self[key].respond_to?(:casted_by)
80
+ else
81
+ klass = ::CouchRest.constantize(target)
82
+ unless self[key].instance_of?(klass)
83
+ self[key] = convert_property_value(property, klass, self[property.name])
84
+ end
85
+ associate_casted_to_parent(self[property.name], assigned)
86
+ end
87
+
88
+ end
89
+
90
+ def associate_casted_to_parent(casted, assigned)
91
+ casted.casted_by = self if casted.respond_to?(:casted_by)
92
+ casted.document_saved = true if !assigned && casted.respond_to?(:document_saved)
93
+ end
94
+
95
+ def convert_property_value(property, klass, value)
96
+ if ((property.init_method == 'new') && klass.to_s == 'Time')
97
+ # Using custom time parsing method because Ruby's default method is toooo slow
98
+ value.is_a?(String) ? Time.mktime_with_offset(value.dup) : value
99
+ # Float instances don't get initialized with #new
100
+ elsif ((property.init_method == 'new') && klass.to_s == 'Float')
101
+ cast_float(value)
102
+ else
103
+ klass.send(property.init_method, value.dup)
104
+ end
105
+ end
106
+
107
+ def cast_property_by_name(property_name)
108
+ return unless self.class.properties
109
+ property = self.class.properties.detect{|property| property.name == property_name}
110
+ return unless property
111
+ cast_property(property, true)
112
+ end
113
+
114
+ def cast_float(value)
115
+ begin
116
+ Float(value)
117
+ rescue
118
+ value
119
+ end
120
+ end
121
+
122
+ module ClassMethods
123
+
124
+ def property(name, options={})
125
+ existing_property = self.properties.find{|p| p.name == name.to_s}
126
+ if existing_property.nil? || (existing_property.default != options[:default])
127
+ define_property(name, options)
128
+ end
129
+ end
130
+
131
+ protected
132
+
133
+ # This is not a thread safe operation, if you have to set new properties at runtime
134
+ # make sure to use a mutex.
135
+ def define_property(name, options={})
136
+ # check if this property is going to casted
137
+ options[:casted] = options[:cast_as] ? options[:cast_as] : false
138
+ property = CouchRest::Property.new(name, (options.delete(:cast_as) || options.delete(:type)), options)
139
+ create_property_getter(property)
140
+ create_property_setter(property) unless property.read_only == true
141
+ properties << property
142
+ end
143
+
144
+ # defines the getter for the property (and optional aliases)
145
+ def create_property_getter(property)
146
+ # meth = property.name
147
+ class_eval <<-EOS, __FILE__, __LINE__
148
+ def #{property.name}
149
+ self['#{property.name}']
150
+ end
151
+ EOS
152
+
153
+ if property.alias
154
+ class_eval <<-EOS, __FILE__, __LINE__
155
+ alias #{property.alias.to_sym} #{property.name.to_sym}
156
+ EOS
157
+ end
158
+ end
159
+
160
+ # defines the setter for the property (and optional aliases)
161
+ def create_property_setter(property)
162
+ property_name = property.name
163
+ class_eval <<-EOS
164
+ def #{property_name}=(value)
165
+ self['#{property_name}'] = value
166
+ cast_property_by_name('#{property_name}')
167
+ end
168
+ EOS
169
+
170
+ if property.alias
171
+ class_eval <<-EOS
172
+ alias #{property.alias.to_sym}= #{property_name.to_sym}=
173
+ EOS
174
+ end
175
+ end
176
+
177
+ end # module ClassMethods
178
+
179
+ end
180
+ end
181
+ end