Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/nub/core.rb

Overview

Monkey patch string with some useful methods

Instance Method Summary collapse

Instance Method Details

#erb(vars = {}) ⇒ Object

Easily inject ERB variables into a string

Parameters:

  • vars (Hash) (defaults to: {})

    of variables to inject into the string



153
154
155
# File 'lib/nub/core.rb', line 153

def erb(vars = {})
  ERBResolve.new(vars).resolve(self)
end

#erb!(vars = {}) ⇒ Object

Easily inject ERB variables into a string

Parameters:

  • vars (Hash) (defaults to: {})

    of variables to inject into the string



159
160
161
# File 'lib/nub/core.rb', line 159

def erb!(vars = {})
  ERBResolve.new(vars).resolve!(self)
end

#strip_colorObject

Strip the ansi color codes from the given string



176
177
178
# File 'lib/nub/core.rb', line 176

def strip_color
  return self.gsub(/\e\[0;[39]\d;49m/, '').gsub(/\e\[0m/, '')
end

#to_asciiObject

Convert the string to ascii, stripping out or converting all non-ascii characters



164
165
166
167
168
169
170
171
172
# File 'lib/nub/core.rb', line 164

def to_ascii
  options = {
    :invalid => :replace,
    :undef => :replace,
    :replace => '',
    :universal_newline => true
  }
  return self.encode(Encoding.find('ASCII'), options)
end

#tokenize_colorObject

Tokenize the given colorized string



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/nub/core.rb', line 182

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