Permalink
Browse files

save! now takes options so you can pass safe in. Might switch the ! m…

…ethods (create!, save! etc.) to just have :safe on by default. Fixes #166.
  • Loading branch information...
1 parent 7289585 commit e21a6c195c9c9f298d61af0e5ebaf5dafadf5a9b @jnunemaker jnunemaker committed Jan 24, 2010
Showing with 46 additions and 4 deletions.
  1. +5 −4 lib/mongo_mapper/document.rb
  2. +41 −0 test/functional/test_document.rb
@@ -350,13 +350,14 @@ def database
end
def save(options={})
+ options.assert_valid_keys(:validate, :safe)
options.reverse_merge!(:validate => true)
- perform_validations = options.delete(:validate)
- !perform_validations || valid? ? create_or_update(options) : false
+ !options[:validate] || valid? ? create_or_update(options) : false
end
- def save!
- save || raise(DocumentNotValid.new(self))
+ def save!(options={})
+ options.assert_valid_keys(:safe)
+ save(options) || raise(DocumentNotValid.new(self))
end
def update_attributes(attrs={})
@@ -763,6 +763,47 @@ def realname=(value)
@document.new(:name => 'John').save(:safe => true)
end
end
+
+ should "raise argument error if options has unsupported key" do
+ doc = @document.new
+ assert_raises(ArgumentError) { doc.save(:foo => true) }
+ end
+ end
+
+ context "#save! (with options)" do
+ setup do
+ MongoMapper.ensured_indexes = []
+
+ @document = Doc do
+ key :name, String
+ set_collection_name 'test_indexes'
+ ensure_index :name, :unique => true
+ end
+
+ if @document.database.collection_names.include?(@document.collection.name)
+ @document.collection.drop_indexes
+ end
+
+ MongoMapper.ensure_indexes!
+ end
+
+ should "allow passing safe" do
+ doc = @document.create(:name => 'John')
+
+ assert_raises(Mongo::OperationFailure) do
+ @document.new(:name => 'John').save!(:safe => true)
+ end
+ end
+
+ should "raise argument error if options has unsupported key" do
+ doc = @document.new
+ assert_raises(ArgumentError) { doc.save!(:foo => true) }
+ end
+
+ should "raise argument error if using validate as that would be pointless with save!" do
+ doc = @document.new
+ assert_raises(ArgumentError) { doc.save!(:validate => false) }
+ end
end
context "#destroy" do

0 comments on commit e21a6c1

Please sign in to comment.