Created
October 31, 2012 13:14
-
-
Save jfredett/3986962 to your computer and use it in GitHub Desktop.
In-memory Software Transactions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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