Skip to content

Commit

Permalink
Merge pull request #92 from tisba/master
Browse files Browse the repository at this point in the history
after_commit callback
  • Loading branch information
alto committed Oct 24, 2013
2 parents 86c24c4 + 41cdf56 commit 080509e
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
9 changes: 8 additions & 1 deletion lib/aasm/persistence/active_record_persistence.rb
Expand Up @@ -132,9 +132,16 @@ def aasm_ensure_initial_state
end

def aasm_fire_event(name, options, *args)
self.class.transaction(:requires_new => true) do
success = self.class.transaction(:requires_new => true) do
super
end

if success
new_state = aasm.state_object_for_name(aasm.current_state)
new_state.fire_callbacks(:after_commit, self)
end

success
end
end # InstanceMethods

Expand Down
15 changes: 14 additions & 1 deletion spec/models/validator.rb
Expand Up @@ -4,13 +4,26 @@ class Validator < ActiveRecord::Base
include AASM
aasm :column => :status do
state :sleeping, :initial => true
state :running
state :running, :after_commit => :change_name!
state :failed, :after_enter => :fail, :after_commit => :change_name!
event :run do
transitions :to => :running, :from => :sleeping
end
event :sleep do
transitions :to => :sleeping, :from => :running
end
event :fail do
transitions :to => :failed, :from => [:sleeping, :running]
end
end
validates_presence_of :name

def change_name!
self.name = "name changed"
save!
end

def fail
raise StandardError.new('failed on purpose')
end
end
17 changes: 17 additions & 0 deletions spec/unit/persistence/active_record_persistence_spec.rb
Expand Up @@ -202,5 +202,22 @@
transactor.should be_running
worker.reload.status.should == 'sleeping'
end

describe "after_commit callback" do
it "should fire :after_commit if transaction was successful" do
validator = Validator.create(:name => 'name')
validator.should be_sleeping
validator.run!
validator.should be_running
validator.name.should_not == "name"
end

it "should not fire :after_commit if transaction failed" do
validator = Validator.create(:name => 'name')
lambda { validator.fail! }.should raise_error(StandardError, 'failed on purpose')
validator.name.should == "name"
end

end
end
end

0 comments on commit 080509e

Please sign in to comment.