Skip to content

Instantly share code, notes, and snippets.

@basgys
Last active October 7, 2015 14:48
Show Gist options
  • Save basgys/3181680 to your computer and use it in GitHub Desktop.
Save basgys/3181680 to your computer and use it in GitHub Desktop.
Retryable transaction
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