Class: IOSegmenter

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/io-segmenter.rb

Overview

IO iterator for parsing segments of streams

Constant Summary collapse

DEFAULT_READ_SIZE =
8192

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, starting_char, ending_char, quote_char, escape_char, max_read_size = DEFAULT_READ_SIZE) ⇒ IOSegmenter

Returns a new instance of IOSegmenter.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/io-segmenter.rb', line 11

def initialize(io, starting_char, ending_char, quote_char, escape_char, max_read_size=DEFAULT_READ_SIZE)
  @io = io
  @starting_char = starting_char
  @ending_char = ending_char
  @quote_char = quote_char
  @escape_char = escape_char
  @max_read_size = max_read_size

  terms = [
    @starting_char,
    @ending_char,
    @quote_char,
    @escape_char
  ]
  terms.compact!
  terms.map! { |str| Regexp.escape(str) }

  @search = Regexp.new('(:?' + terms.join('|') + ')')
  @buffer = String.new
end

Instance Attribute Details

#bufferObject (readonly)

Returns the value of attribute buffer.



9
10
11
# File 'lib/io-segmenter.rb', line 9

def buffer
  @buffer
end

Class Method Details

.foreach(*args, &block) ⇒ Object



47
48
49
# File 'lib/io-segmenter.rb', line 47

def self.foreach(*args, &block)
  new(*args).each(&block)
end

Instance Method Details

#eachObject



32
33
34
35
36
37
38
# File 'lib/io-segmenter.rb', line 32

def each
  until @io.eof?
    unpack(@io.read(@max_read_size)) do |segment|
      yield segment
    end
  end
end

#unpack(str) ⇒ Object



40
41
42
43
44
45
# File 'lib/io-segmenter.rb', line 40

def unpack(str)
  @buffer << str
  each_segment(@buffer) do |segment|
    yield segment
  end
end