Skip to content

Instantly share code, notes, and snippets.

@cainlevy
Created October 28, 2011 21:19
Show Gist options
  • Save cainlevy/1323593 to your computer and use it in GitHub Desktop.
Save cainlevy/1323593 to your computer and use it in GitHub Desktop.

Revisions

  1. cainlevy revised this gist Oct 28, 2011. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions with_retries.rb
    Original file line number Diff line number Diff line change
    @@ -8,11 +8,16 @@ module Retriable
    # This will catch a specific exception and retry once (two tries total):
    # with_retries(Some::Error, :limit => 2) { ... }
    #
    # You can also sleep inbetween tries. This is helpful if you're hoping
    # that some external service recovers from its issues.
    # with_retries(Service::Error, :sleep => 1) { ... }
    #
    def with_retries(*args, &block)
    options = args.extract_options!
    exceptions = args

    options[:limit] ||= 3
    options[:sleep] ||= 0
    exceptions = [Exception] if exceptions.empty?

    retried = 0
    @@ -21,6 +26,7 @@ def with_retries(*args, &block)
    rescue *exceptions => e
    if retried + 1 < options[:limit]
    retried += 1
    sleep options[:sleep]
    retry
    else
    raise e
  2. cainlevy created this gist Oct 28, 2011.
    35 changes: 35 additions & 0 deletions with_retries.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    module Retriable
    # This will catch any exception and retry twice (three tries total):
    # with_retries { ... }
    #
    # This will catch any exception and retry four times (five tries total):
    # with_retries(:limit => 5) { ... }
    #
    # This will catch a specific exception and retry once (two tries total):
    # with_retries(Some::Error, :limit => 2) { ... }
    #
    def with_retries(*args, &block)
    options = args.extract_options!
    exceptions = args

    options[:limit] ||= 3
    exceptions = [Exception] if exceptions.empty?

    retried = 0
    begin
    yield
    rescue *exceptions => e
    if retried + 1 < options[:limit]
    retried += 1
    retry
    else
    raise e
    end
    end
    end
    end

    class Object
    include Retriable
    extend Retriable
    end