Permalink
Browse files

Initial import.

  • Loading branch information...
1 parent a5d3fb3 commit 5d602cbacfb13e9ddfa98dc045938b08d63a693f @carlo committed Jan 10, 2009
Showing with 60 additions and 0 deletions.
  1. 0 README
  2. +42 −0 README.markdown
  3. +18 −0 lib/retryable.rb
View
0 README
No changes.
View
@@ -0,0 +1,42 @@
+# Kernel#retryable
+
+## Description
+
+Runs a code block, and retries it when an exception occurs. It's great when
+working with flakey webservices (for example).
+
+It's configured using two optional parameters --`:tries` and `:on`--, and
+runs the passed block. Should an exception occur, it'll retry for (n-1) times.
+
+Should the number of retries be reached without success, the last exception
+will be returned/raised.
+
+
+## Examples
+
+1. Open an URL, retry up to two times when an `OpenURI::HTTPError` occurs.
+
+ retryable( :tries => 3, :on => OpenURI:HTTPError ) do
+ xml = open( xml_url ).read
+ end
+
+2. Do _something_, retry up to four times for either `ArgumentError` or
+ `TimeoutError` exceptions.
+
+ retryable( :tries => 5, :on => [ ArgumentError, TimeoutError ] ) do
+ # some crazy code
+ end
+
+
+## Defaults
+
+ :tries => 1, :on => Exception
+
+
+## Installation
+
+First, [make sure GitHub is a gem source](http://gems.github.com/). Then, install the gem:
+
+ sudo gem install carlo-retryable
+
+
View
@@ -0,0 +1,18 @@
+# Code originally by Chu Yeow, see
+# http://blog.codefront.net/2008/01/14/retrying-code-blocks-in-ruby-on-exceptions-whatever/
+# Slightly rewritten to allow for passing of more than just type of exception.
+
+def retryable( options = {}, &block )
+ opts = { :tries => 1, :on => Exception }.merge(options)
+
+ retry_exception, retries = [ opts[:on] ].flatten, opts[:tries]
+
+ begin
+ return yield
+ rescue *retry_exception
+ retry if (retries -= 1) > 0
+ end
+
+ yield
+end
+

0 comments on commit 5d602cb

Please sign in to comment.