Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make after_commit work reliabliy inside nested transactions #338

Merged
merged 6 commits into from
Feb 22, 2019
Merged
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
36 changes: 35 additions & 1 deletion lib/statesman/adapters/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,20 @@ def create_transition(from, to, metadata)
transition.save!
@last_transition = transition
@observer.execute(:after, from, to, transition)
add_after_commit_callback(from, to, transition)
end
@observer.execute(:after_commit, from, to, transition)

transition
end

def add_after_commit_callback(from, to, transition)
::ActiveRecord::Base.connection.add_transaction_record(
ActiveRecordAfterCommitWrap.new do
@observer.execute(:after_commit, from, to, transition)
end,
)
end

def transitions_for_parent
@parent_model.send(@association_name)
end
Expand Down Expand Up @@ -149,5 +157,31 @@ def with_updated_timestamp(params)
params.merge(column => timestamp)
end
end

class ActiveRecordAfterCommitWrap
def initialize
@callback = Proc.new
@connection = ::ActiveRecord::Base.connection
end

# rubocop: disable Naming/PredicateName
def has_transactional_callbacks?
true
end
# rubocop: enable Naming/PredicateName

def committed!(*)
@callback.call
end

def before_committed!(*); end

def rolledback!(*); end

# Required for +transaction(requires_new: true)+
def add_to_transaction(*)
@connection.add_transaction_record(self)
end
end
end
end