1
0
Fork 0
mirror of https://github.com/aasm/aasm synced 2023-03-27 23:22:41 -04:00

make sure the 2 fields are in sync by using before_validation_on_create

This commit is contained in:
Jeff Dean 2008-04-29 01:58:05 -04:00
parent cb6bd4f534
commit a0bb1c404c
2 changed files with 33 additions and 0 deletions

View file

@ -33,6 +33,7 @@ module AASM
base.send(:include, AASM::Persistence::ActiveRecordPersistence::ReadState) unless base.method_defined?(:aasm_read_state)
base.send(:include, AASM::Persistence::ActiveRecordPersistence::WriteState) unless base.method_defined?(:aasm_write_state)
base.send(:include, AASM::Persistence::ActiveRecordPersistence::WriteStateWithoutPersistence) unless base.method_defined?(:aasm_write_state_without_persistence)
base.before_validation_on_create :aasm_ensure_initial_state
end
module ClassMethods
@ -91,6 +92,20 @@ module AASM
@current_state = aasm_read_state
end
private
# Called from before_validation_on_create to ensure
# that if there is a nil value in the underlying aasm_state
# column, the initial state is used instead
#
# foo = Foo.new
# foo.save
# foo.aasm_state # => the initial state
#
def aasm_ensure_initial_state
send("#{self.class.aasm_column}=", self.aasm_current_state.to_s)
end
end
module WriteStateWithoutPersistence

View file

@ -157,6 +157,24 @@ begin
foo.aasm_current_state.should be_nil
end
it "should have aasm_ensure_initial_state" do
foo = Foo.new
foo.send :aasm_ensure_initial_state
end
it "should call aasm_ensure_initial_state on validation before create" do
foo = Foo.new
foo.should_receive(:aasm_ensure_initial_state).and_return(true)
foo.valid?
end
it "should call aasm_ensure_initial_state on validation before create" do
foo = Foo.new
foo.stub!(:new_record?).and_return(false)
foo.should_not_receive(:aasm_ensure_initial_state)
foo.valid?
end
end
# TODO: figure out how to test ActiveRecord reload! without a database