Skip to content
This repository has been archived by the owner on Apr 17, 2018. It is now read-only.

Commit

Permalink
Only validate a dirty resource when saving
Browse files Browse the repository at this point in the history
* Prevents multiple validations when saving parent and children, since
  previously every child that was saved would tell the parent to
  save too.  Now the parent will be saved, and will not be be dirty
  any longer, so the unnecessary validation will be skipped.

[#1154 state:resolved]
  • Loading branch information
dkubb committed Feb 2, 2010
1 parent 716eb50 commit 178bc58
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion dm-validations/lib/dm-validations.rb
Expand Up @@ -57,7 +57,7 @@ def update(attributes = {}, context = default_validation_context)

chainable do
def save_self(*)
return false unless validation_context_stack.empty? || valid?(current_validation_context)
return false unless !dirty_self? || validation_context_stack.empty? || valid?(current_validation_context)
super
end
end
Expand Down
8 changes: 8 additions & 0 deletions dm-validations/spec/fixtures/barcode.rb
Expand Up @@ -2,6 +2,7 @@ module DataMapper
module Validate
module Fixtures
class Barcode
attr_accessor :valid_hook_call_count

#
# Behaviors
Expand All @@ -26,6 +27,13 @@ class Barcode
def self.valid_instance
new(:code => "3600029145")
end

# measure the number of times #valid? is executed
before :valid? do
@valid_hook_call_count ||= 0
@valid_hook_call_count += 1
end

end # Barcode
end
end
Expand Down
38 changes: 38 additions & 0 deletions dm-validations/spec/public/resource_spec.rb
Expand Up @@ -64,4 +64,42 @@
end
end
end

describe '#save' do
before :all do
@resource.code = 'a' * 10
@resource.save
end

describe 'on a new resource' do
it 'should call valid? once' do
@resource.valid_hook_call_count.should == 1
end
end

describe 'on a saved, non-dirty resource' do
before :all do
# reload the resource
@resource = @resource.model.get(*@resource.key)
@resource.save
end

it 'should not call valid?' do
@resource.valid_hook_call_count.should be_nil
end
end

describe 'on a saved, dirty resource' do
before :all do
# reload the resource
@resource = @resource.model.get(*@resource.key)
@resource.code = 'b' * 10
@resource.save
end

it 'should call valid? once' do
@resource.valid_hook_call_count.should == 1
end
end
end
end

0 comments on commit 178bc58

Please sign in to comment.