Skip to content

Commit

Permalink
Refactor wrapper
Browse files Browse the repository at this point in the history
This brings the wrapper class in line with the others.

The class is now constructed via the options passed to `#use`,
which means we don't need to change the signature of any methods,
which was not ideal.

  stack = GH::Stack.build do
    use GH::Retry, retries: 10
  end

  GH.with(stack) { GH['users/rkh'] }

Also renames the `sleep` option to `wait`.
  • Loading branch information
joecorcoran committed Jul 18, 2016
1 parent 802fab4 commit e23cc49
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
29 changes: 17 additions & 12 deletions lib/gh/retry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,34 @@ module GH
class Retry < Wrapper
DEFAULTS = {
retries: 5,
sleep: 1
wait: 1
}

def [](key, opts = {})
generate_response key, fetch_resource(key, opts)
attr_accessor :retries, :wait

def initialize(backend = nil, options = {})
options = DEFAULTS.merge options
super backend, options
end

def fetch_resource(key, opts = {})
opts = DEFAULTS.merge opts
retries, sleep_time = opts[:retries], opts[:sleep]
def fetch_resource(key)
begin
retries -= 1
super(key)
decrement_retries!
super key
rescue GH::Error(response_status: 404) => e
raise(e) unless retries_remaining?(retries)
sleep sleep_time
fetch_resource key, retries: retries, sleep: sleep_time
retries_remaining? or raise e
sleep wait
fetch_resource key
end
end

private

def retries_remaining?(retries)
def decrement_retries!
self.retries = self.retries - 1
end

def retries_remaining?
retries > 0
end
end
Expand Down
4 changes: 2 additions & 2 deletions spec/retry_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ def fetch_resource(key)
end
end

before { subject.backend = not_finder.new }
subject { described_class.new(not_finder.new, retries: 3, wait: 0.1) }

it 'retries request specified number of times' do
expect { subject['users/not-found', retries: 3, sleep: 0.1] }.to raise_error(GH::Error)
expect { subject['users/not-found'] }.to raise_error(GH::Error)
expect(subject.backend.requests.count).to eq 3
end

Expand Down

0 comments on commit e23cc49

Please sign in to comment.