Skip to content

Instantly share code, notes, and snippets.

@gnomex
Created August 15, 2020 23:31
Show Gist options
  • Select an option

  • Save gnomex/d2438c0c1a4d25a0a27ddda7de4a9911 to your computer and use it in GitHub Desktop.

Select an option

Save gnomex/d2438c0c1a4d25a0a27ddda7de4a9911 to your computer and use it in GitHub Desktop.

Revisions

  1. gnomex created this gist Aug 15, 2020.
    57 changes: 57 additions & 0 deletions retryable.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    def inject_strategy(max_retries)
    (1..max_retries).inject(nil) do |result, attempt_number|
    begin
    return yield if block_given?
    rescue => e
    # intentionally blank
    end
    end
    end

    def retry_strategy(max_retries)
    tries ||= 0

    begin
    yield if block_given?
    rescue => e
    return if tries >= max_retries

    tries += 1

    retry
    end
    end

    def times_strategy(max_retries)
    max_retries.times do |index|
    begin
    return yield if block_given?
    rescue => e
    # intentionally blank
    end
    end
    end

    require 'benchmark/ips'

    Benchmark.ips do |x|
    x.report('with retries') do
    retry_strategy(5) do
    raise "some error to allow the benchmark"
    end
    end

    x.report('with inject') do
    inject_strategy(5) do
    raise "some error to allow the benchmark"
    end
    end

    x.report('with times') do
    times_strategy(5) do
    raise "some error to allow the benchmark"
    end
    end

    x.compare!
    end