Class: Markbridge::Parsers::BBCode::PeekableEnumerator
- Inherits:
-
Object
- Object
- Markbridge::Parsers::BBCode::PeekableEnumerator
- Defined in:
- lib/markbridge/parsers/bbcode/peekable_enumerator.rb
Overview
Wrapper around a scanner that allows peeking at upcoming tokens without consuming them.
This class buffers tokens pulled from a scanner (which must implement
next_token) so callers can:
- inspect the next token with #peek without advancing the scanner
- inspect several upcoming tokens with #peek_ahead
- consume tokens with #next (returns
nilwhen exhausted)
The enumerator is lazy: tokens are only requested from the scanner
when needed. Once the underlying scanner returns nil, the enumerator
is marked finished and further peeks return nil (for single peeks)
or an empty array (for multi-peeks).
Instance Method Summary collapse
-
#initialize(scanner) ⇒ PeekableEnumerator
constructor
Initialize a new PeekableEnumerator.
-
#next ⇒ Object?
(also: #next_token)
Consume and return the next token.
-
#peek ⇒ Object?
Peek at the next single token without consuming it.
-
#peek_ahead(count) ⇒ Array<Object>
Peek ahead at up to
countupcoming tokens without consuming them.
Constructor Details
#initialize(scanner) ⇒ PeekableEnumerator
Initialize a new PeekableEnumerator.
32 33 34 35 |
# File 'lib/markbridge/parsers/bbcode/peekable_enumerator.rb', line 32 def initialize(scanner) @scanner = scanner @peeked = [] end |
Instance Method Details
#next ⇒ Object? Also known as: next_token
Consume and return the next token.
39 40 41 42 |
# File 'lib/markbridge/parsers/bbcode/peekable_enumerator.rb', line 39 def next ensure_peeked(1) @peeked.shift end |
#peek ⇒ Object?
Peek at the next single token without consuming it.
46 47 48 49 |
# File 'lib/markbridge/parsers/bbcode/peekable_enumerator.rb', line 46 def peek ensure_peeked(1) @peeked.first end |
#peek_ahead(count) ⇒ Array<Object>
Peek ahead at up to count upcoming tokens without consuming them.
54 55 56 57 58 |
# File 'lib/markbridge/parsers/bbcode/peekable_enumerator.rb', line 54 def peek_ahead(count) count = [count, 0].max ensure_peeked(count) @peeked.first(count) end |