Class: Tryout

Inherits:
Object
  • Object
show all
Defined in:
lib/tryout.rb,
lib/tryout/version.rb

Overview

Allows you to do dirty stuff without messing up your code base.

Constant Summary collapse

VERSION =

Gem Version

'0.1.1'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Tryout

Initializes Tryout with the content retrieval logic.

Parameters:

  • block (block)

    content retrieval logic



20
21
22
23
# File 'lib/tryout.rb', line 20

def initialize(&block)
  @attempts = 0
  @block = block
end

Class Method Details

.try(&block) ⇒ Tryout

Initialize the Tryout instance.

Examples:

value = Tryout.try { RestClient.get('http://www.google.com') }.retry(3, :if => :empty?)

Parameters:

  • block (block)

    content retrieval logic

Returns:



12
13
14
# File 'lib/tryout.rb', line 12

def self.try &block
  self.new(&block)
end

Instance Method Details

#retry(times = 2, conditions = {}, &evaluator) ⇒ Object

Retry the block call

Parameters:

  • times (Integer) (defaults to: 2)

    (default: 2)

  • conditions (Hash) (defaults to: {})
  • [Symbol] (Hash)

    a customizable set of options

Returns:

  • (Object)

    result from block call



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tryout.rb', line 33

def retry(times = 2, conditions = {}, &evaluator)
  result = @block.call

  # Call block to evaluate valid result
  if block_given?
    conditions = { :match => evaluator.call(result) }
  end

  # Throw a exception to be rescued, if retry count reached the limit.
  if apply_conditions?(result, conditions)
    throw Exception.new("#{result.inspect} doesn't match conditions. Already retried #{times.inspect} times.")
  end

  result
rescue Exception => e
  @attempts += 1
  if @attempts < times
    retry
  else
    raise e
  end
end