class FileTransactions::Transaction

A class that keeps track of commands and nested transactions. If an exception is raised inside the transaction, then all commands and nested transactions get undone.

Attributes

backrolled[RW]
block[R]
commands[R]

Public Class Methods

new(&block) click to toggle source
# File lib/file_transactions/transaction.rb, line 23
def initialize(&block)
  raise Error, 'A block must be given' unless block_given?

  @block = block
  @commands = []
end
run(&block) click to toggle source
# File lib/file_transactions/transaction.rb, line 9
def run(&block)
  new(&block).__send__(:run)
end
scope() click to toggle source
# File lib/file_transactions/transaction.rb, line 17
def scope
  Thread.current['FT.scope']
end
scope=(scope) click to toggle source
# File lib/file_transactions/transaction.rb, line 13
def scope=(scope)
  Thread.current['FT.scope'] = scope
end

Public Instance Methods

backrolled?() click to toggle source
# File lib/file_transactions/transaction.rb, line 42
def backrolled?
  !!backrolled
end
register(command) click to toggle source
# File lib/file_transactions/transaction.rb, line 30
def register(command)
  commands << command
end
rollback() click to toggle source
# File lib/file_transactions/transaction.rb, line 34
def rollback
  return if backrolled?

  commands.reverse_each(&:undo)
  self.backrolled = true
end
Also aliased as: undo
undo()
Alias for: rollback

Private Instance Methods

run() click to toggle source
# File lib/file_transactions/transaction.rb, line 51
def run
  scope = Transaction.scope
  scope&.register self
  Transaction.scope = self
  block.call
rescue StandardError => e
  rollback
  raise unless Rollback === e
ensure
  Transaction.scope = scope
end