F1e3ab214a976a39cfd713bc93deb10f

I know &block does not need to be present, but i prefer to have it shown, makes it more obvious that blocks are allowed IMO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  ##
  # Retry a _block_ of statements upto a number of _times_.
  # When no error is raised the value returned by _block_ is 
  # simply returned.
  #
  # === Examples
  #
  #   try 3 do
  #     open 'http://vision-media.ca'
  #   end
  #   # => allows 3 tries to fetch the response
  #
  
  def try times = 1, options = {}, &block
    yield
  rescue options[:on] || Exception
    retry if (times -= 1) > 0
  end

Refactorings

No refactoring yet !

F4192eeb4b26e96deab8b5c68926105d

Muke Tever

October 12, 2009, October 12, 2009 12:15, permalink

1 rating. Login to rate!

Well, it looks fine. Though IMO it looks like it ought to be parallel to "3.times do", so:

1
2
3
4
5
6
7
8
9
class Integer
  def tries options = {}, &block
    return if self < 1
    yield attempts ||= 1
  rescue options[:ignoring] || Exception
    retry if (attempts += 1) <= self
  end
end

Examples

1
2
3
4
5
6
7
8
9
10
11
12
3.tries { open 'http://vision-media.ca' }

3.tries do |i| 
  puts "Try ##{i} at opening..."
  open 'http://vision-media.ca' 
end

3.tries(:ignoring => ParticularException) do
  open 'http://vision-media.ca' 
end

# etc.

Your refactoring





Format Copy from initial code

or Cancel