Class: Redd::Utilities::Stream

Inherits:
Object
  • Object
show all
Defined in:
lib/redd/utilities/stream.rb

Overview

A forward-expading listing of items that can be enumerated forever.

Defined Under Namespace

Classes: RingBuffer

Instance Method Summary collapse

Constructor Details

#initialize {|Models::Listing| ... } ⇒ Stream

Create a streamer.

Yields:

Yield Parameters:

Yield Returns:


29
30
31
32
33
# File 'lib/redd/utilities/stream.rb', line 29

def initialize(&block)
  @loader = block
  @buffer = RingBuffer.new(100)
  @previous = nil
end

Instance Method Details

#next_request {|element| ... } ⇒ Object

Make another request to reddit, yielding new elements.

Yields:

  • (element)

    an element from the listings returned by the loader


37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/redd/utilities/stream.rb', line 37

def next_request
  # Get the elements from the loader before the `latest` element
  listing = @loader.call(@previous)
  # If there's nothing new to process, request again.
  return if listing.empty?
  # Iterate over the new elements, oldest to newest.
  listing.reverse_each do |el|
    next if @buffer.include?(el.name)
    yield el
    @buffer.add(el.name)
  end
  # Store the last successful listing
  @previous = listing
end

#stream {|element| ... } ⇒ Object

Loop forever, yielding the elements from the loader

Yields:

  • (element)

    an element from the listings returned by the loader


54
55
56
57
58
# File 'lib/redd/utilities/stream.rb', line 54

def stream
  loop do
    next_request { |el| yield el }
  end
end