Class: BlockReader

Inherits:
Object
  • Object
show all
Includes:
LogUtils::Logging
Defined in:
lib/textutils/reader/block_reader.rb

Overview

fix: move into TextUtils namespace/module!!

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ BlockReader

Returns a new instance of BlockReader.



21
22
23
# File 'lib/textutils/reader/block_reader.rb', line 21

def initialize( text )
  @text = text
end

Class Method Details

.from_file(path) ⇒ Object



10
11
12
13
14
15
# File 'lib/textutils/reader/block_reader.rb', line 10

def self.from_file( path )
  ## nb: assume/enfore utf-8 encoding (with or without BOM - byte order mark)
  ## - see textutils/utils.rb
 text = File.read_utf8( path )
 self.from_string( text )
end

.from_string(text) ⇒ Object



17
18
19
# File 'lib/textutils/reader/block_reader.rb', line 17

def self.from_string( text )
  self.new( text )
end

Instance Method Details

#readObject



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
64
# File 'lib/textutils/reader/block_reader.rb', line 25

def read
  ## note returns an array of (line) strings e.g.
  ## [
  ##  "line1\nline2",         ## -- block1
  ##  "line1\nline2\nline3"   ## -- block2
  ## ]

  blocks = []
  buf = ""

  @text.each_line do |line|
     # comments allow:
     # 1) ##### (shell/ruby style)
     if line =~ /^\s*#/ 
        # skip komments and do NOT copy to result (keep comments secret!)
       logger.debug 'skipping comment line'
       next
     end

#       if line =~ /^\s*$/
#         # kommentar oder leerzeile überspringen
#         logger.debug 'skipping blank line'
#         next
#       end

     # pass 2) remove leading and trailing whitespace
     line = line.strip

     if line =~ /^-{3,}$/   ## three or more lines
       logger.debug 'block separator'
       blocks << buf.strip   ## note: strip leading and trailing whitespace
       buf = ""
     else
       buf << "#{line}\n"
     end
  end # each lines

  blocks << buf.strip ## note: strip leading and trailing whitespace
  blocks
end