Class: String

Inherits:
Object show all
Defined in:
lib/garcon/core_ext/string.rb

Overview

Author: Stefano Harding <[email protected]> License: Apache License, Version 2.0 Copyright: © 2014-2015 Stefano Harding

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Instance Method Summary collapse

Instance Method Details

#/(other) ⇒ String

Join with o as a file path.

Examples:

'usr'/'local' # => 'usr/local'

Parameters:

  • other (String)

    Path component(s) to join with receiver.

Returns:

  • (String)

    Receiver joined with other as a file path.



193
194
195
# File 'lib/garcon/core_ext/string.rb', line 193

def /(other)
  File.join(self, other.to_s)
end

#blackObject



280
# File 'lib/garcon/core_ext/string.rb', line 280

def black;      colorize(self, "\e[0;30m"); end

#blank?Boolean

Strips out whitespace then tests if the string is empty.

"".blank?         #=>  true
"     ".blank?    #=>  true
" hey ho ".blank? #=>  false

Returns:



78
79
80
# File 'lib/garcon/core_ext/string.rb', line 78

def blank?
  strip.empty?
end


277
# File 'lib/garcon/core_ext/string.rb', line 277

def blink;      colorize(self, "\e[5m");    end

#blueObject



288
# File 'lib/garcon/core_ext/string.rb', line 288

def blue;       colorize(self, "\e[0;34m"); end

#boldObject



274
# File 'lib/garcon/core_ext/string.rb', line 274

def bold;       colorize(self, "\e[1m");    end

#bright_redObject



295
# File 'lib/garcon/core_ext/string.rb', line 295

def bright_red; colorize(self, "\e[1;41m"); end

#clearObject



271
# File 'lib/garcon/core_ext/string.rb', line 271

def clear;      colorize(self, "\e[0m");    end

#colorize(text, color_code) ⇒ Object



305
# File 'lib/garcon/core_ext/string.rb', line 305

def colorize(text, color_code) "#{color_code}#{text}\e[0m" end

#compress_lines(spaced = true) ⇒ String

Replace sequences of whitespace (including newlines) with either a single space or remove them entirely (according to param spaced)

Examples:

<<QUERY.compress_lines
  SELECT name
  FROM users
QUERY => 'SELECT name FROM users'

Parameters:

  • spaced (Boolean) (defaults to: true)

    (default=true) Determines whether returned string has whitespace collapsed or removed

Returns:

  • (String)

    Receiver with whitespace (including newlines) replaced



229
230
231
# File 'lib/garcon/core_ext/string.rb', line 229

def compress_lines(spaced = true)
  split($/).map { |line| line.strip }.join(spaced ? ' ' : '')
end

#concealedObject



279
# File 'lib/garcon/core_ext/string.rb', line 279

def concealed;  colorize(self, "\e[8m");    end

#contains?(str) ⇒ Boolean

Search a text file for a matching string

Returns:

  • (Boolean)

    True if the file is present and a match was found, otherwise returns false if file does not exist and/or does not contain a match



46
47
48
49
50
# File 'lib/garcon/core_ext/string.rb', line 46

def contains?(str)
  return false unless ::File.exist?(self)
  ::File.open(self, &:readlines).collect { |l| return true if l.match(str) }
  false
end

#creamObject



287
# File 'lib/garcon/core_ext/string.rb', line 287

def cream;      colorize(self, "\e[1;33m"); end

#crypt(salt = nil) ⇒ Object

Common Unix cryptography method. This adds a default salt to the built-in crypt method.



31
32
33
34
35
36
37
# File 'lib/garcon/core_ext/string.rb', line 31

def crypt(salt = nil)
  salt ||= ((SecureRandom.random_number(26) +
            (SecureRandom.random_number(2) == 0 ? 65 : 97)).chr +
            (SecureRandom.random_number(26) +
            (SecureRandom.random_number(2) == 0 ? 65 : 97)).chr)
  _crypt(salt)
end

#cyanObject



292
# File 'lib/garcon/core_ext/string.rb', line 292

def cyan;       colorize(self, "\e[0;36m"); end

#cyan2Object



293
# File 'lib/garcon/core_ext/string.rb', line 293

def cyan2;      colorize(self, "\e[1;36m"); end

#darkObject



275
# File 'lib/garcon/core_ext/string.rb', line 275

def dark;       colorize(self, "\e[2m");    end

#erase_charObject



273
# File 'lib/garcon/core_ext/string.rb', line 273

def erase_char; colorize(self, "\e[P");     end

#erase_lineObject



272
# File 'lib/garcon/core_ext/string.rb', line 272

def erase_line; colorize(self, "\e[K");     end

#escape_regexpString

Escape all regexp special characters.

Examples:

"*?{}.".escape_regexp   # => "\\*\\?\\{\\}\\."

Returns:

  • (String)

    Receiver with all regexp special characters escaped.



137
138
139
# File 'lib/garcon/core_ext/string.rb', line 137

def escape_regexp
  Regexp.escape self
end

#flushString

Left-flush a string based off of the number of whitespace characters on the first line. This is especially useful for heredocs when whitespace matters.

Examples:

Remove leading whitespace and flush

<<-EOH.flush
  def method
    'This is a string!'
  end
EOH # =>"def method\n  'This is a string!'\nend"

Returns:



124
125
126
# File 'lib/garcon/core_ext/string.rb', line 124

def flush
  gsub(/^#{self[/\A\s*/]}/, '').chomp
end

#grayObject



281
# File 'lib/garcon/core_ext/string.rb', line 281

def gray;       colorize(self, "\e[1;30m"); end

#greenObject



284
# File 'lib/garcon/core_ext/string.rb', line 284

def green;      colorize(self, "\e[0;32m"); end

#light_grayObject



294
# File 'lib/garcon/core_ext/string.rb', line 294

def light_gray; colorize(self, "\e[2;37m"); end

#magentaObject



283
# File 'lib/garcon/core_ext/string.rb', line 283

def magenta;    colorize(self, "\e[1;31m"); end

#margin(indicator = nil) ⇒ String

Remove whitespace margin.

Returns:

  • (String)

    Receiver with whitespace margin removed.



239
240
241
242
243
244
245
246
247
248
249
# File 'lib/garcon/core_ext/string.rb', line 239

def margin(indicator = nil)
  lines = self.dup.split($/)

  min_margin = 0
  lines.each do |line|
    if line =~ /^(\s+)/ && (min_margin == 0 || $1.size < min_margin)
      min_margin = $1.size
    end
  end
  lines.map { |line| line.sub(/^\s{#{min_margin}}/, '') }.join($/)
end

#mustardObject



291
# File 'lib/garcon/core_ext/string.rb', line 291

def mustard;    colorize(self, "\e[1;35m"); end

#object_state(data = nil) ⇒ Object

Get or set state of object. You can think of #object_state as an in-code form of marshalling.



24
25
26
# File 'lib/garcon/core_ext/string.rb', line 24

def object_state(data = nil)
  data ? replace(data) : dup
end

#oliveObject



285
# File 'lib/garcon/core_ext/string.rb', line 285

def olive;      colorize(self, "\e[1;32m"); end

#on_blackObject



297
# File 'lib/garcon/core_ext/string.rb', line 297

def on_black;   colorize(self, "\e[40m");   end

#on_blueObject



301
# File 'lib/garcon/core_ext/string.rb', line 301

def on_blue;    colorize(self, "\e[44m");   end

#on_cyanObject



303
# File 'lib/garcon/core_ext/string.rb', line 303

def on_cyan;    colorize(self, "\e[46m");   end

#on_greenObject



299
# File 'lib/garcon/core_ext/string.rb', line 299

def on_green;   colorize(self, "\e[42m");   end

#on_magentaObject



302
# File 'lib/garcon/core_ext/string.rb', line 302

def on_magenta; colorize(self, "\e[45m");   end

#on_redObject



298
# File 'lib/garcon/core_ext/string.rb', line 298

def on_red;     colorize(self, "\e[41m");   end

#on_whiteObject



304
# File 'lib/garcon/core_ext/string.rb', line 304

def on_white;   colorize(self, "\e[47m");   end

#on_yellowObject



300
# File 'lib/garcon/core_ext/string.rb', line 300

def on_yellow;  colorize(self, "\e[43m");   end

#orangeObject



290
# File 'lib/garcon/core_ext/string.rb', line 290

def orange;     colorize(self, "\e[0;35m"); end

#purpleObject



289
# File 'lib/garcon/core_ext/string.rb', line 289

def purple;     colorize(self, "\e[1;34m"); end

#redObject



282
# File 'lib/garcon/core_ext/string.rb', line 282

def red;        colorize(self, "\e[0;31m"); end

#relative_path_from(other) ⇒ String

Calculate a relative path from other.

Examples:

'/opt/chefdk/'.relative_path_from '/opt/chefdk/embedded/bin' # => '../..'

Parameters:

  • other (String)

    Base path to calculate from.

Returns:

  • (String)

    Relative path from other to receiver.



209
210
211
# File 'lib/garcon/core_ext/string.rb', line 209

def relative_path_from(other)
  Pathname.new(self).relative_path_from(Pathname.new(other)).to_s
end

#reverseObject



278
# File 'lib/garcon/core_ext/string.rb', line 278

def reverse;    colorize(self, "\e[7m");    end

#shatter(re) ⇒ String

Breaks a string up into an array based on a regular expression. Similar to scan, but includes the matches.

Examples:

s = "<p>This<b>is</b>a test.</p>"
s.shatter(/\<.*?\>/)
  => [
    [0] "<p>",
    [1] "This",
    [2] "<b>",
    [3] "is",
    [4] "</b>",
    [5] "a test.",
    [6] "</p>"
  ]

Parameters:

  • regex (Regexp)

    Regular expression for breaking string into array.

Returns:



104
105
106
107
108
109
# File 'lib/garcon/core_ext/string.rb', line 104

def shatter(re)
  r = self.gsub(re) { |s| "\1" + s + "\1" }
  while r[ 0, 1] == "\1";  r[0] = ''; end
  while r[-1, 1] == "\1"; r[-1] = ''; end
  r.split("\1")
end

#t(*values) ⇒ String

Formats String for easy translation. Replaces an arbitrary number of values using numeric identifier replacement.

Examples:

"%s %s %s" % %w(one two three)        # => 'one two three'
"%3$s %2$s %1$s" % %w(one two three)  # => 'three two one'

Parameters:

  • values (#to_s)

    A list of values to translate and interpolate into receiver

Returns:

  • (String)

    Receiver translated with values translated and interpolated positionally



265
266
267
268
269
# File 'lib/garcon/core_ext/string.rb', line 265

def t(*values)
  self.class::translate(self) % values.collect! do |value|
    value.frozen? ? value : self.class::translate(value.to_s)
  end
end

#to_const_pathString

Convert a constant name to a path, assuming a conventional structure.

Examples:

"FooBar::Baz".to_const_path # => "foo_bar/baz"

Returns:

  • (String)

    Path to the file containing the constant named by receiver (constantized string), assuming a conventional structure.



177
178
179
# File 'lib/garcon/core_ext/string.rb', line 177

def to_const_path
  snake_case.gsub(/::/, "/")
end

#to_const_stringString

Convert a path string to a constant name.

Examples:

"chef/mixin/checksum".to_const_string # => "Chef::Mixin::Checksum"

Returns:

  • (String)

    Receiver converted to a constant name.



163
164
165
# File 'lib/garcon/core_ext/string.rb', line 163

def to_const_string
  gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
end

#to_re(esc = false) ⇒ Object

Turns a string into a regular expression.

"a?".to_re  #=> /a?/


56
57
58
# File 'lib/garcon/core_ext/string.rb', line 56

def to_re(esc = false)
  Regexp.new((esc ? Regexp.escape(self) : self))
end

#to_rx(esc = true) ⇒ Object

Turns a string into a regular expression. By default it will escape all characters. Use false argument to turn off escaping.

"[".to_rx  #=> /\[/


66
67
68
# File 'lib/garcon/core_ext/string.rb', line 66

def to_rx(esc = true)
  Regexp.new((esc ? Regexp.escape(self) : self))
end

#underlineObject



276
# File 'lib/garcon/core_ext/string.rb', line 276

def underline;  colorize(self, "\e[4m");    end

#unescape_regexpString

Unescape all regexp special characters.

Examples:

"\\*\\?\\{\\}\\.".unescape_regexp # => "*?{}."

Returns:

  • (String)

    Receiver with all regexp special characters unescaped.



150
151
152
# File 'lib/garcon/core_ext/string.rb', line 150

def unescape_regexp
  self.gsub(/\\([\.\?\|\(\)\[\]\{\}\^\$\*\+\-])/, '\1')
end

#whiteObject



296
# File 'lib/garcon/core_ext/string.rb', line 296

def white;      colorize(self, "\e[0;97m"); end

#yellowObject



286
# File 'lib/garcon/core_ext/string.rb', line 286

def yellow;     colorize(self, "\e[0;33m"); end