summaryrefslogtreecommitdiff
path: root/components/stream.rb
blob: 45c4a2bc7e1248cb3e2c2e18ba954299378e193f (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# frozen_string_literal: true

require 'stringio'

module NanoBot
  module Components
    class Stream < StringIO
      def write(*args)
        if @callback
          @accumulated += args.first
          @callback.call(@accumulated, args.first, false)
        end
        super
      end

      def callback=(block)
        @accumulated = ''
        @callback = block
      end

      def finish
        flush
        result = string.clone
        truncate(0)
        rewind

        if @callback
          @callback.call(@accumulated, nil, true)
          @callback = nil
          @accumulated = nil
        end

        result
      end
    end
  end
end