Class: BlockRepeater::Repeater

Inherits:
Object
  • Object
show all
Includes:
RepeaterMethods
Defined in:
lib/block_repeater/repeater.rb

Constant Summary

Constants included from RepeaterMethods

RepeaterMethods::UNTIL_METHOD_REGEX

Instance Method Summary collapse

Methods included from RepeaterMethods

#call_if_method_responsive, #method_missing, #respond_to_missing?

Constructor Details

#initialize(manual_repeat: true, **kwargs, &block) ⇒ Repeater

Prepare the Repeater to take the initial block to be repeated

Parameters:

  • manual_repeat (defaults to: true)
    • Determines whether the repeat method needs to called manually, used by the Repeatable module

  • **kwargs
    • Capture other arguments in the situation where repeat isn’t being called manually

  • &block
    • The block of code to be repeated



19
20
21
22
23
# File 'lib/block_repeater/repeater.rb', line 19

def initialize(manual_repeat: true, **kwargs, &block)
  @manual_repeat = manual_repeat
  @repeater_arguments = kwargs
  @repeat_block = block
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class RepeaterMethods

Instance Method Details

#repeat(times: 25, delay: 0.2, **_) ⇒ Object

Repeat a block until either the defined timeout is met or the condition block returns true

Parameters:

  • times (defaults to: 25)
    • How many times to attempt to execute the main block

  • delay (defaults to: 0.2)
    • The amount of time to wait between each attempt

  • **_
    • Capture any extra keyword arguments and discard them

Returns:

  • The result of calling the main block the final time



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/block_repeater/repeater.rb', line 32

def repeat(times: 25, delay: 0.2, **_)
  result, @condition_met, exception = nil
  times.times do
    result = @repeat_block.call
    begin
      @condition_met = @condition_block.call(result) if @condition_block
      exception = nil
    rescue RSpec::Expectations::ExpectationNotMetError => e
      exception = e
    end
    break if @condition_met

    sleep delay
  end

  raise exception if exception

  result
end

#until(&block) ⇒ Object

Set the block which determines if the main block should stop being executed

Parameters:

  • &block
    • The block of code which determines the target condition of the main block

Returns:

  • Either return the repeater object if the repeat method is being called manually or return the result of calling the repeat method



58
59
60
61
62
63
64
65
# File 'lib/block_repeater/repeater.rb', line 58

def until(&block)
  @condition_block = block
  if @manual_repeat
    self
  else
    repeat **@repeater_arguments
  end
end