Class: Kumogata::StringStream

Inherits:
Object
  • Object
show all
Defined in:
lib/kumogata/string_stream.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ StringStream

Returns a new instance of StringStream.



2
3
4
5
6
7
8
9
10
11
12
# File 'lib/kumogata/string_stream.rb', line 2

def initialize(&block)
  @buf = StringScanner.new('')
  @block = block

  @fiber = Fiber.new do
    self.run
  end

  # Step to `yield`
  @fiber.resume
end

Instance Method Details

#closeObject



34
35
36
37
38
# File 'lib/kumogata/string_stream.rb', line 34

def close
  self.each_line
  @block.call(@buf.rest) if @buf.rest?
  @fiber.resume
end

#each_lineObject



24
25
26
27
28
# File 'lib/kumogata/string_stream.rb', line 24

def each_line
  while (line = @buf.scan_until(/(\r\n|\r|\n)/))
    @block.call(line.chomp)
  end
end

#push(chunk) ⇒ Object



30
31
32
# File 'lib/kumogata/string_stream.rb', line 30

def push(chunk)
  @fiber.resume(chunk)
end

#runObject



14
15
16
17
18
19
20
21
22
# File 'lib/kumogata/string_stream.rb', line 14

def run
  loop do
    chunk = Fiber.yield
    break unless chunk

    @buf << chunk.to_s
    self.each_line
  end
end