Class: Boring

Inherits:
Object
  • Object
show all
Defined in:
lib/boring.rb,
lib/version.rb

Constant Summary collapse

ESCAPE_SEQUENCE =

ANSI Escape sequence byte ranges:

CSI Parameter bytes: “0123456789:;<=>?” CSI Intermediate bytes: “ !"#$%&‘()*+,-./” CSI Finishing byte: “@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~”

References: en.wikipedia.org/wiki/ANSI_escape_code

https://www.gnu.org/software/teseq/manual/html_node/Escape-Sequence-Recognition.html
/
  \x1B             # Escape sequences start with an ESC char
  ( 
    [\x20-\x2F]*
    [\x40-\x5A\x5C-\x7E]
    
    |
    
    \[               # Start CSI sequence
    [\x30-\x3F]+     # CSI Parameter bytes
    [\x20-\x2F]*     # CSI Intermediate bytes
    [\x40-\x7E]      # CSI Finishing byte  
  )
/x
REPLACEMENT =

Default escape replacement

""
VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(replacement = REPLACEMENT) ⇒ Boring

Create a new Boring string scrubber. An optional replacement string may be used for any ANSI escape sequences.



35
36
37
# File 'lib/boring.rb', line 35

def initialize(replacement=REPLACEMENT)
  @replacement = replacement
end

Instance Attribute Details

#replacementObject (readonly)

Returns the value of attribute replacement.



31
32
33
# File 'lib/boring.rb', line 31

def replacement
  @replacement
end

Instance Method Details

#pipe(io_in, io_out) ⇒ Object

Pipe data from io_in to io_out and scrub it along the way.



40
41
42
43
44
45
46
# File 'lib/boring.rb', line 40

def pipe(io_in, io_out)
  # Since we know that an escape may not contain a newline, we can process
  # this line by line.
  io_in.each_line do |line|
    io_out << scrub(line)
  end
end

#scrub(str) ⇒ Object

Removes escape sequences from str.



49
50
51
# File 'lib/boring.rb', line 49

def scrub(str)
  str.gsub(ESCAPE_SEQUENCE, replacement)
end

#scrub!(str) ⇒ Object

Removes escape sequences from str in place.



54
55
56
57
# File 'lib/boring.rb', line 54

def scrub!(str)
  str.gsub!(ESCAPE_SEQUENCE, replacement)
  str
end