Skip to content

Commit

Permalink
Added save! for rails compatibility.
Browse files Browse the repository at this point in the history
  • Loading branch information
jnunemaker committed Jun 18, 2009
1 parent 0184824 commit 05b4241
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
6 changes: 6 additions & 0 deletions lib/mongo_mapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@

module MongoMapper
class DocumentNotFound < StandardError; end
class DocumentNotValid < StandardError
def initialize(document)
@document = document
super("Validation failed: #{@document.errors.full_messages.join(", ")}")
end
end

def self.connection
@@connection ||= XGen::Mongo::Driver::Mongo.new
Expand Down
6 changes: 5 additions & 1 deletion lib/mongo_mapper/save_with_validation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ def self.included(base)
end
end

private
def save!
save_with_validation || raise(DocumentNotValid.new(self))
end

private
def save_with_validation
new? ? run_callbacks(:before_validation_on_create) :
run_callbacks(:before_validation_on_update)
Expand Down
16 changes: 16 additions & 0 deletions test/test_validations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,22 @@ class ValidationsTest < Test::Unit::TestCase
end
end

context "Saving a document that is invalid (destructive)" do
setup do
@document = Class.new do
include MongoMapper::Document
key :name, String, :required => true
end

@document.collection.clear
end

should "raise error" do
doc = @document.new
lambda { doc.save! }.should raise_error(MongoMapper::DocumentNotValid)
end
end

context "Saving an existing document that is invalid" do
setup do
@document = Class.new do
Expand Down

0 comments on commit 05b4241

Please sign in to comment.