Class: ObjectForge::Sequence
- Inherits:
-
Object
- Object
- ObjectForge::Sequence
- Defined in:
- lib/object_forge/sequence.rb
Overview
A thread-safe representation of a sequence of values.
Instance Attribute Summary collapse
-
#initial ⇒ #succ
readonly
Initial value for the sequence.
Class Method Summary collapse
-
.new(initial) ⇒ Sequence
Return a new sequence, or
initialif it’s already a sequence.
Instance Method Summary collapse
-
#initialize(initial) ⇒ Sequence
constructor
A new instance of Sequence.
-
#next ⇒ #succ
Get the next value in the sequence, starting with the initial value.
-
#reset ⇒ #succ
(also: #rewind)
Reset the sequence to its #initial value.
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.
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.
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.
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.
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.
53 54 55 |
# File 'lib/object_forge/sequence.rb', line 53 def reset @container.modify { @initial } end |