Skip to content

Commit

Permalink
executing after_commit callback after another model transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
sevaorlov committed Mar 16, 2015
1 parent 43a6b97 commit 929ccfa
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/after_commit_action.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ module AfterCommitAction
end

def execute_after_commit(&block)
if ActiveRecord::Base.connection.open_transactions == 0 ||
ActiveRecord::Base.connection.add_transaction_record(self).nil?
return block.call
end

@_execute_after_commit ||= []
@_execute_after_commit<< block
end
Expand Down
18 changes: 18 additions & 0 deletions spec/after_commit_action_spec.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

require 'models/tester'
require 'models/another_model'

describe "AfterCommitAction" do
it "should correctly execute tasks after commit" do
Expand All @@ -18,4 +19,21 @@
t.array.should include('before_update')
t.array.should include('after_update')
end

context 'when block is executed in another model transaction' do
let(:tester) { Tester.create count: 0 }
let(:another_model) { AnotherModel.new tester: tester }

subject { another_model.save! }

it { expect { subject }.to change { tester.reload.count }.from(0).to 1 }
end

context 'when there is no transaction' do
let(:tester) { Tester.create count: 0 }

subject { tester.increment_counter }

it { expect { subject }.to change { tester.reload.count }.from(0).to 1 }
end
end
11 changes: 11 additions & 0 deletions spec/models/another_model.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class AnotherModel < ActiveRecord::Base
include AfterCommitAction

belongs_to :tester

after_save :increment_tester_counter

def increment_tester_counter
tester.increment_counter
end
end
4 changes: 4 additions & 0 deletions spec/models/tester.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,8 @@ def before_update
def after_update
execute_after_commit { @array<< 'after_update' }
end

def increment_counter
execute_after_commit { increment! :count }
end
end
5 changes: 5 additions & 0 deletions spec/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@

create_table "testers", :force => true do |t|
t.string "name"
t.integer "count", :default => 0
end

create_table "another_models", :force => true do |t|
t.string "tester_id"
end

end

0 comments on commit 929ccfa

Please sign in to comment.