Skip to content

Commit

Permalink
Refactored transaction state into its own object. Each transaction cr…
Browse files Browse the repository at this point in the history
…eates a new transaction state object upon initialization.
  • Loading branch information
wangjohn committed Jan 21, 2013
1 parent 4e32722 commit 26853e8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,36 @@ class Transaction #:nodoc:

def initialize(connection)
@connection = connection
@state = nil
@state = TransactionState.new
end

def state
@state
end
end

class TransactionState

VALID_STATES = Set.new([:committed, :rolledback, nil])

def initialize(state = nil)
@state = state
end

def committed?
@state == :commit
@state == :committed
end

def rolledback?
@state == :rollback
@state == :rolledback
end

def set_state(state)
if !VALID_STATES.include?(state)
raise ArgumentError, "Invalid transaction state: #{state}"
end
@state = state
end
end

class ClosedTransaction < Transaction #:nodoc:
Expand Down Expand Up @@ -101,7 +120,7 @@ def add_record(record)
end

def rollback_records
@state = :rollback
@state.set_state(:rolledback)
records.uniq.each do |record|
begin
record.rolledback!(parent.closed?)
Expand All @@ -112,7 +131,7 @@ def rollback_records
end

def commit_records
@state = :commit
@state.set_state(:committed)
records.uniq.each do |record|
begin
record.committed!
Expand Down
12 changes: 10 additions & 2 deletions activerecord/test/cases/transactions_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -456,19 +456,27 @@ def test_transactions_state_from_rollback
transaction = ActiveRecord::ConnectionAdapters::ClosedTransaction.new(connection).begin

assert transaction.open?
assert !transaction.state.rolledback?
assert !transaction.state.committed?

transaction.perform_rollback

assert transaction.rolledback?
assert transaction.state.rolledback?
assert !transaction.state.committed?
end

def test_transactions_state_from_commit
connection = Topic.connection
transaction = ActiveRecord::ConnectionAdapters::ClosedTransaction.new(connection).begin

assert transaction.open?
assert !transaction.state.rolledback?
assert !transaction.state.committed?

transaction.perform_commit

assert transaction.committed?
assert !transaction.state.rolledback?
assert transaction.state.committed?
end

private
Expand Down

0 comments on commit 26853e8

Please sign in to comment.