Skip to content

Instantly share code, notes, and snippets.

@jfredett
Created October 31, 2012 13:14
Show Gist options
  • Save jfredett/3986962 to your computer and use it in GitHub Desktop.
Save jfredett/3986962 to your computer and use it in GitHub Desktop.
In-memory Software Transactions
lass TransactionalHash < Hash
def transaction
old = dup
begin
return tap { yield(self) }
rescue Exception => e
clear
old.each do |k,v|
self[k] = v
end
raise e
end
end
end
class Transaction
def self.start(obj)
new(obj)
end
def assign_object(obj)
@version = obj
self
end
def initialize(obj)
@version = obj
@actions = []
end
def perform(&block)
@actions << block
self
end
def commit
old = @version
@actions.each do |a|
@version = a.call(@version)
end
return @version
rescue Exception => e
@version = old
raise e
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment