Module: FirePoll

Defined in:
lib/fire_poll.rb,
lib/fire_poll/version.rb

Overview

see the README file for instruction on how to use this library

Constant Summary collapse

VERSION =
"1.2.0"

Class Method Summary collapse

Class Method Details

.patiently(seconds = nil, delay = nil) { ... } ⇒ Object

Runs a block of code and returns the value. IF ANYTHING raises in the block due to test failure or error, the exception will be held, a small delay, then re-try the block. This patience endures for 5 seconds by default, before the most recent reason for failure gets re-raised.

Parameters:

  • seconds (Numeric) (defaults to: nil)

    Wall-clock number of seconds to be patient, default is 5 seconds

  • delay (Numeric) (defaults to: nil)

    Seconds to hesitate after encountering a failure, default is 0.1 seconds

Yields:

  • a block that will be run, and if it raises an error, re-run until success, or patience runs out

Returns:

  • the value of the passed block

Raises:

  • (Exception)

    the most recent Exception that caused the loop to retry before giving up.

Since:

  • 1.2.0



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/fire_poll.rb', line 42

def patiently(seconds=nil, delay=nil)
  seconds ||= 5                   # 5 seconds overall patience
  give_up_at = Time.now + seconds # pick a time to stop being patient
  delay ||= 0.1                   # wait a tenth of a second before re-attempting
  failure = nil                   # record the most recent failure

  while Time.now < give_up_at do
    begin
      return yield
    rescue Exception => e
      failure = e
      sleep delay              # avoid spinning like crazy
    end
  end
  
  if failure
    raise failure # if we never got satisfaction, tell the world
  end
end

.poll(msg = nil, seconds = nil) { ... } ⇒ Object

Returns the return value of the passed block.

Parameters:

  • msg (String) (defaults to: nil)

    a custom message raised when polling fails

  • seconds (Numeric) (defaults to: nil)

    number of seconds to poll

Yields:

  • a block that determines whether polling should continue

  • return false if polling should continue

  • return true if polling is complete

Returns:

  • the return value of the passed block

Raises:

  • (RuntimeError)

    when polling fails

Since:

  • 1.0.0



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/fire_poll.rb', line 11

def poll(msg=nil, seconds=nil) 
  seconds ||= 2.0                 # 5 seconds overall patience
  give_up_at = Time.now + seconds # pick a time to stop being patient
  delay = 0.1                     # wait a tenth of a second before re-attempting
  failure = nil                   # record the most recent failure

  while Time.now < give_up_at do
    result = yield
    return result if result
    sleep delay
  end
  msg ||= "polling failed after #{seconds} seconds" 
  raise msg
end