class Redd::Utilities::Stream

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

Public Class Methods

new(&block) click to toggle source

Create a streamer. @yield [Models::Listing] @yieldparam previous [Models::Listing] the result of the last request @yieldreturn [Models::Listing] the models after the latest one

# File lib/redd/utilities/stream.rb, line 29
def initialize(&block)
  @loader = block
  @buffer = RingBuffer.new(100)
  @previous = nil
end

Public Instance Methods

next_request() { |el| ... } click to toggle source

Make another request to reddit, yielding new elements. @yield [element] an element from the listings returned by the loader

# 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() { |el| ... } click to toggle source

Loop forever, yielding the elements from the loader @yield [element] an element from the listings returned by the loader

# File lib/redd/utilities/stream.rb, line 54
def stream
  loop do
    next_request { |el| yield el }
  end
end