Revision b150389d143b () - Diff

Link to this snippet: https://friendpaste.com/7muwOf6JdrSe7N4YqgHLnU
Embed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
diff --git a/lib/couchrest/core/model.rb b/lib/couchrest/core/model.rb
index 463eed5..8ce8569 100644
--- a/lib/couchrest/core/model.rb
+++ b/lib/couchrest/core/model.rb
@@ -93,6 +93,7 @@ module CouchRest
class_inheritable_accessor :generated_design_doc
class_inheritable_accessor :design_doc_slug_cache
class_inheritable_accessor :design_doc_fresh
+ class_inheritable_accessor :validation_fields
class << self
# override the CouchRest::Model-wide default_database
@@ -171,6 +172,10 @@ module CouchRest
self.default_obj = hash
end
+ def validate *fields
+ self.validation_fields = fields.map {|f| f.to_s}
+ end
+
# Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
# on the document whenever saving occurs. CouchRest uses a pretty
# decent time format by default. See Time#to_json
@@ -444,12 +449,25 @@ module CouchRest
!rev
end
+ def valid?
+ self.invalid_fields.blank?
+ end
+
+ def invalid_fields
+ return [] unless self.validation_fields
+ check = self.validation_fields.clone
+ self.validation_fields.each do |c|
+ check.delete_if {|x| x == c } if !self[c].blank?
+ end
+ return check
+ end
+
# Saves the document to the db using create or update. Also runs the :save
# callbacks. Sets the <tt>_id</tt> and <tt>_rev</tt> fields based on
# CouchDB's response.
def save
if new_record?
- create
+ if self.valid? then create else return false end
else
update
end