Class: Philiprehberger::TestFactory::Sequence

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/test_factory/sequence.rb

Overview

Thread-safe auto-incrementing sequence generator.

Examples:

seq = Sequence.new { |n| "user_#{n}@example.com" }
seq.next # => "user_1@example.com"
seq.next # => "user_2@example.com"

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Sequence

Create a new sequence.

Parameters:

  • block (Proc)

    block receiving an integer counter (starting at 1)



15
16
17
18
19
# File 'lib/philiprehberger/test_factory/sequence.rb', line 15

def initialize(&block)
  @block = block
  @counter = 0
  @mutex = Mutex.new
end

Instance Method Details

#nextObject

Increment the counter and return the block result.

Returns:

  • (Object)

    the result of the block with the current counter



24
25
26
27
28
29
# File 'lib/philiprehberger/test_factory/sequence.rb', line 24

def next
  @mutex.synchronize do
    @counter += 1
    @block.call(@counter)
  end
end