Skip to content

Commit

Permalink
save! now takes options so you can pass safe in. Might switch the ! m…
Browse files Browse the repository at this point in the history
…ethods (create!, save! etc.) to just have :safe on by default. Fixes mongomapper#166.
  • Loading branch information
jnunemaker committed Jan 24, 2010
1 parent 7289585 commit e21a6c1
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib/mongo_mapper/document.rb
Expand Up @@ -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={})
Expand Down
41 changes: 41 additions & 0 deletions test/functional/test_document.rb
Expand Up @@ -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
Expand Down

0 comments on commit e21a6c1

Please sign in to comment.