Class: ObjectForge::Sequence

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

Overview

A thread-safe representation of a sequence of values.

Since:

  • 0.1.0

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial) ⇒ Sequence

Note:

Initial value must not be modified after the sequence is created, or the results will be unpredicatable. Consider always passing a frozen value.

Returns a new instance of Sequence.

Parameters:

  • initial (#succ)

    initial value for the sequence

Raises:

  • (ArgumentError)

    if initial does not respond to #succ

Since:

  • 0.1.0



29
30
31
32
33
34
35
36
# File 'lib/object_forge/sequence.rb', line 29

def initialize(initial)
  unless initial.respond_to?(:succ)
    raise ArgumentError, "initial value must respond to #succ, #{initial.class} given"
  end

  @initial = initial
  @container = Concurrent::MVar.new(initial) # steep:ignore UnknownConstant
end

Instance Attribute Details

#initial#succ (readonly)

Returns initial value for the sequence.

Returns:

  • (#succ)

    initial value for the sequence

Since:

  • 0.1.0



21
22
23
# File 'lib/object_forge/sequence.rb', line 21

def initial
  @initial
end

Class Method Details

.new(initial) ⇒ Sequence

Return a new sequence, or initial if it’s already a sequence.

Parameters:

Returns:

Since:

  • 0.1.0



14
15
16
17
18
# File 'lib/object_forge/sequence.rb', line 14

def self.new(initial, ...)
  return initial if initial.is_a?(Sequence)

  super
end

Instance Method Details

#next#succ

Get the next value in the sequence, starting with the initial value.

Returns:

  • (#succ)

    next value

Since:

  • 0.1.0



44
45
46
# File 'lib/object_forge/sequence.rb', line 44

def next
  @container.modify(&:succ)
end

#reset#succ Also known as: rewind

Reset the sequence to its #initial value.

Returns:

  • (#succ)

    whatever value would be returned by #next before reset

Since:

  • 0.1.0



53
54
55
# File 'lib/object_forge/sequence.rb', line 53

def reset
  @container.modify { @initial }
end