Class: Markbridge::Parsers::BBCode::PeekableEnumerator

Inherits:
Object
  • Object
show all
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 ‘nil` when 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).

Examples:

Basic usage

scanner = YourScanner.new("...") # responds to `next_token`
enum = PeekableEnumerator.new(scanner)
enum.peek        # => next token (no consume)
enum.peek_ahead(3) # => array of up to 3 upcoming tokens
enum.next        # => consumes and returns next token

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(scanner) ⇒ PeekableEnumerator

Initialize a new PeekableEnumerator.

Parameters:

  • scanner (Object)

    the scanner object that responds to ‘next_token`



32
33
34
35
# File 'lib/markbridge/parsers/bbcode/peekable_enumerator.rb', line 32

def initialize(scanner)
  @scanner = scanner
  @peeked = []
end

Instance Method Details

#nextObject? Also known as: next_token

Consume and return the next token.

Returns:

  • (Object, nil)

    next token or ‘nil` when exhausted



39
40
41
42
# File 'lib/markbridge/parsers/bbcode/peekable_enumerator.rb', line 39

def next
  ensure_peeked(1)
  @peeked.shift
end

#peekObject?

Peek at the next single token without consuming it.

Returns:

  • (Object, nil)

    the next token or ‘nil` when exhausted



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.

Parameters:

  • count (Integer)

    number of tokens to peek ahead (clamped to 0..)

Returns:

  • (Array<Object>)

    array of upcoming tokens (possibly empty)



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