Class: Termplot::Consumer

Inherits:
Object
  • Object
show all
Defined in:
lib/termplot/consumer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Consumer

Returns a new instance of Consumer.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/termplot/consumer.rb', line 10

def initialize(options)
  @options = options
  @renderer = Renderer.new(
    cols: options.cols,
    rows: options.rows,
    debug: options.debug
  )
  @series = Series.new(
    title: options.title,
    max_data_points: renderer.inner_width,
    line_style: options.line_style,
    color: options.color,
  )
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



8
9
10
# File 'lib/termplot/consumer.rb', line 8

def options
  @options
end

#rendererObject (readonly)

Returns the value of attribute renderer.



8
9
10
# File 'lib/termplot/consumer.rb', line 8

def renderer
  @renderer
end

#seriesObject (readonly)

Returns the value of attribute series.



8
9
10
# File 'lib/termplot/consumer.rb', line 8

def series
  @series
end

Instance Method Details

#runObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/termplot/consumer.rb', line 25

def run
  Shell.init
  queue = Queue.new

  # Consumer thread will process and render any available input in the
  # queue. If samples are available faster than it can render, multiple
  # samples will be shifted from the queue so they can be rendered at once.
  # If no samples are available but the queue is open, it will sleep until
  # woken to render new input.
  consumer = Thread.new do
    while !queue.closed?
      num_samples = queue.size
      if num_samples == 0
        Thread.stop
      else
        num_samples.times do
          series.add_point(queue.shift)
        end

        renderer.render(series)
        series.max_data_points = renderer.inner_width
      end
    end
  end

  # Producer will run in the main thread and will block while producing
  # samples from some source (which depends on the type of producer).
  # Samples will be added to the queue as they are available, and the
  # consumer will be woken to check the queue
  producer = build_producer(queue)
  producer.register_consumer(consumer)
  producer.run

  # As soon as producer continues, and we first give the consumer a chance
  # to finish rendering the queue, then close the queue.
  consumer.run
  producer.close
  consumer.join
end