Class: Pagetience::Meditate

Inherits:
Object
  • Object
show all
Defined in:
lib/pagetience/meditate.rb

Constant Summary collapse

DEFAULT_TIMEOUT_MESSAGE =
'Timed out waiting for the expected result.'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timeout = 30, polling = 1, &block) ⇒ Meditate

Returns a new instance of Meditate.



16
17
18
19
20
# File 'lib/pagetience/meditate.rb', line 16

def initialize(timeout=30, polling=1, &block)
  @timeout = timeout
  @polling = polling
  @block = block
end

Instance Attribute Details

#blockObject

Returns the value of attribute block.



5
6
7
# File 'lib/pagetience/meditate.rb', line 5

def block
  @block
end

#pollingObject

Returns the value of attribute polling.



5
6
7
# File 'lib/pagetience/meditate.rb', line 5

def polling
  @polling
end

#timeoutObject

Returns the value of attribute timeout.



5
6
7
# File 'lib/pagetience/meditate.rb', line 5

def timeout
  @timeout
end

Class Method Details

.for(opts, &block) ⇒ Object



8
9
10
11
12
13
# File 'lib/pagetience/meditate.rb', line 8

def for(opts, &block)
  opts[:timeout] ||= 30
  opts[:polling] ||= 1
  opts[:msg] ||= DEFAULT_TIMEOUT_MESSAGE
  Meditate.new(opts[:timeout], opts[:polling]) { block.call }.until_enlightened opts[:expecting], opts[:msg]
end

Instance Method Details

#until_enlightened(expected = nil, msg = DEFAULT_TIMEOUT_MESSAGE) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pagetience/meditate.rb', line 22

def until_enlightened(expected=nil, msg=DEFAULT_TIMEOUT_MESSAGE)
  raise ArgumentError, 'Timeout cannot be lower than the polling value.' unless @timeout > @polling

  while @timeout > 0 && @timeout > @polling
    @latest_result = @block.call
    break if @latest_result == expected
    sleep @polling
    @timeout = @timeout - @polling
  end

  msg = msg.send(:call) if msg.is_a? Proc
  raise Pagetience::TimeoutError, msg unless @latest_result == expected

  @latest_result
end