Permalink
Browse files

Refactored transaction state into its own object. Each transaction cr…

…eates a new transaction state object upon initialization.
  • Loading branch information...
1 parent 4e32722 commit 26853e8948167b7388244ef67f0480211ad2d9f5 @wangjohn wangjohn committed Jan 20, 2013
@@ -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:
@@ -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?)
@@ -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!
@@ -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

0 comments on commit 26853e8

Please sign in to comment.