Last active
October 7, 2015 14:48
-
-
Save basgys/3181680 to your computer and use it in GitHub Desktop.
Retryable transaction
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
class ActiveRecord::Base | |
# Retryable transaction | |
# ===================== | |
# | |
# Author : Bastien Gysler (http://www.bastiengysler.com) | |
# | |
# ActiveRecord::Base.retryable_transaction(tries: 1, :when => ActiveRecord::RecordNotUnique) do |on| | |
# on.transaction do | |
# # transaction code here | |
# end | |
# on.success do | |
# # success code here | |
# end | |
# on.error do |ex| | |
# # error code here | |
# end | |
# end | |
# | |
def self.retryable_transaction(args = {}, &block) | |
retries = args[:tries] || 1 | |
begin | |
self.transaction do | |
block.callback :transaction | |
end | |
block.callback :success | |
rescue args[:when] || ActiveRecord::Errors => e | |
retry if (retries -= 1) >= 0 | |
block.callback :error, e | |
end | |
end | |
end | |
# Author : Mat Sears (http://mattsears.com/) | |
class Proc | |
def callback(callable, *args) | |
self === Class.new do | |
method_name = callable.to_sym | |
define_method(method_name) { |&block| block.nil? ? true : block.call(*args) } | |
define_method("#{method_name}?") { true } | |
def method_missing(method_name, *args, &block) false; end | |
end.new | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment