Skip to content
This repository was archived by the owner on Apr 17, 2018. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/dm-validations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ def update(attributes = {}, context = default_validation_context)
end

chainable do
def save_self(*)
return false unless !dirty_self? || validation_context_stack.empty? || valid?(current_validation_context)
def save_self(execute_hooks = true, *args)
return false unless !dirty_self? || !execute_hooks || validation_context_stack.empty? || valid?(current_validation_context)
super
end
end
Expand Down
58 changes: 58 additions & 0 deletions spec/fixtures/bill.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
module DataMapper
module Validations
module Fixtures

# Simple class that represents a bill. This example was
# chosen because bills sometimes need corrections while
# keeping the originals
class Bill
include DataMapper::Resource

property :id, DataMapper::Property::Serial

# property to make sure the resource is marked as dirty
property :has_correction, DataMapper::Property::Boolean

# convenience association to be able to get to the original
# bill if this is the correction
has 1, :original, :model => 'BillCorrection'

# Keep track of the amount of time the valid hook is called
attr_accessor :valid_hook_call_count

def valid?(context = :default)
@valid_hook_call_count ||= 0
@valid_hook_call_count += 1
super
end
end

# correction of a bill creates a new bill which keeps an
# association to the original bill
class BillCorrection
include DataMapper::Resource

property :id, DataMapper::Property::Serial

belongs_to :original_bill, :model => 'Bill'
belongs_to :correction_bill, :model => 'Bill'

def self.build_from(original, intermediary = nil)
correction = Bill.new
correction.original = self.new(:original_bill => original, :correction_bill => correction )
correction
end

def save
if save_result = super
original_bill.has_correction = true
# suppose we want to bypass validation for some reason
original_result = original_bill.save!
end
save_result && original_result
end
end
end
end
end

14 changes: 14 additions & 0 deletions spec/public/resource_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,17 @@
end
end
end

describe '#save!' do
it "should not call valid when save! is used" do
bill = DataMapper::Validations::Fixtures::Bill.new()
bill.save.should be_true

bill_correction = DataMapper::Validations::Fixtures::BillCorrection.build_from(bill)

# bill_correction.save will call save! on @bill
bill_correction.save.should be_true

bill.valid_hook_call_count.should == 1
end
end