Browse files

Add validation hooks

Change-Id: Icda04f2b64688ded435cb31b0912092375ff33d3
  • Loading branch information...
1 parent b37cba7 commit 7ac15e2fd6455da189bbc4de5596ba9b4db0bb72 @avsej committed Sep 25, 2012
Showing with 14 additions and 0 deletions.
  1. +1 −0 lib/couchbase-model.rb
  2. +13 −0 lib/couchbase/model.rb
View
1 lib/couchbase-model.rb
@@ -24,5 +24,6 @@
class Couchbase::Model
extend ActiveModel::Naming
include ActiveModel::Conversion
+ include ActiveModel::Validations
end
end
View
13 lib/couchbase/model.rb
@@ -37,6 +37,15 @@ module Couchbase
# @since 0.0.1
class Error::MissingId < Error::Base; end
+ # @since 0.4.0
+ class Error::RecordInvalid < Error::Base
+ attr_reader :record
+ def initialize(record)
+ @record = record
+ super(@record.errors.full_messages.join(", "))
+ end
+ end
+
# Declarative layer for Couchbase gem
#
# @since 0.0.1
@@ -414,6 +423,7 @@ def self.create(*args)
#
# @param [Hash] attrs attribute-value pairs
def initialize(attrs = {})
+ @errors = ::ActiveModel::Errors.new(self) if defined?(::ActiveModel)
case attrs
when Hash, HashWithIndifferentAccess
if attrs.respond_to?(:with_indifferent_access)
@@ -469,6 +479,9 @@ def create
# p.draft = false
# p.save
def save(cas = nil)
+ if respond_to?(:valid?) && !valid?
+ raise Couchbase::Error::RecordInvalid.new(self)
+ end
return create if new?
value = @_raw ? @_raw : attributes_with_values
model.bucket.replace(@id, value, model.default.merge(:cas => cas))

0 comments on commit 7ac15e2

Please sign in to comment.