Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/nub/string.rb
Overview
Monkey patch string with some useful methods
Instance Method Summary collapse
-
#strip_color ⇒ Object
Strip the ansi color codes from the given string.
-
#to_ascii ⇒ Object
Convert the string to ascii, stripping out or converting all non-ascii characters.
-
#tokenize_color ⇒ Object
Tokenize the given colorized string.
Instance Method Details
#strip_color ⇒ Object
Strip the ansi color codes from the given string
51 52 53 |
# File 'lib/nub/string.rb', line 51 def strip_color return self.gsub(/\e\[0;[39]\d;49m/, '').gsub(/\e\[0m/, '') end |
#to_ascii ⇒ Object
Convert the string to ascii, stripping out or converting all non-ascii characters
39 40 41 42 43 44 45 46 47 |
# File 'lib/nub/string.rb', line 39 def to_ascii = { :invalid => :replace, :undef => :replace, :replace => '', :universal_newline => true } return self.encode(Encoding.find('ASCII'), ) end |
#tokenize_color ⇒ Object
Tokenize the given colorized string
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/nub/string.rb', line 57 def tokenize_color tokens = [] matches = self.to_enum(:scan, /\e\[0;[39]\d;49m(.*?[\s]*)\e\[0m/).map{Regexp.last_match} i, istart, iend = 0, 0, 0 match = matches[i] while istart < self.size color = "39" iend = self.size token = self[istart..iend] # Current token is not a match if match && match.begin(0) != istart iend = match.begin(0)-1 token = self[istart..iend] istart = iend + 1 # Current token is a match elsif match && match.begin(0) == istart iend = match.end(0) token = match.captures.first color = match.to_s[/\e\[0;(\d+);49m.*/, 1] i += 1; match = matches[i] istart = iend # Ending else istart = iend end # Create token and advance tokens << ColorPair.new(token, color.to_i, ColorMap[color.to_i]) end return tokens end |