Super transaction plugin
Plugin details
Documentation
ruby script/plugin install http://code.stat.im/repos/plugins/super_transaction/tags/0.9/
==Examples
user = User.new(:login => "login", :password => "password") book = Book.new(:title => "title") page = Page.new(:summary => "summary")
Pass super_transaction a list of the objects that must pass for this transaction to be committed
Note: Make sure you pass these
book.user = user page.book = book ok = super_transaction(user, book, page) do user.save book.save page.save end ok #=> true
super_transaction always returns true or false. As long as you pass the correct objects as parameters, true means a COMMIT took place, false means a ROLLBACK took place
So the idea is you can write the procedure the same way you would if you weren't using a transaction. But, you get all of the benefits that you would if you had rolled your own #transaction call and accounted for all of the error/exception/validation handling for free.
For convenience, #super_transaction is defined in Object as well and just passes along to ActiveRecord::Base.super_transaction, which allows you to just call #super_transaction anywhere.
WHAT WOULD IT LOOK LIKE WITHOUT super_transaction? (an explanation for the need super_transaction fills):
user = User.new(:login => "login", :password => "password") book = Book.new(:title => "title") page = Page.new(:summary => "summary") book.user = user page.book = book models = [user, book, page] ok = true begin ActiveRecord::Base.transaction do raise unless models.inject(true) { |s, model| model.save && s } end rescue ok = false end ok #=> true
OK, so not terrible. It achives the same goals (in this case), but its cryptic and limiting. It limits us to #save for the models we pass in. But its the best bet before super_transaction in order to make sure we try to call #save on everything and not stop at the first failure
Here's a not so diligent way that doesnt fit my requirements:
ok = true begin ActiveRecord::Base.transaction do raise unless user.save raise unless book.save raise unless page.save end rescue ok = false end ok #=> true
This one stops at the first failure, so we dont get validations on book or page if user fails to save. Ok, so we could call #valid? on each model beforehand, but then it starts to get ugly. Plus, what if an error is added in an #after_ method?
Further Documentation
There is currently no advanced documentation for this plugin.
New documentationEdit plugin | Back in time (1 older version) | Last edited by: scott, about 1 year ago


