class String

Author: Stefano Harding <riddopic@gmail.com> 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.

Public Instance Methods

/(other) click to toggle source

Join with o as a file path.

@example

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

@param [String] other

Path component(s) to join with receiver.

@return [String]

Receiver joined with other as a file path.

@api public

# File lib/garcon/core_ext/string.rb, line 193
def /(other)
  File.join(self, other.to_s)
end
black() click to toggle source
# File lib/garcon/core_ext/string.rb, line 280
def black;      colorize(self, "\e[0;30m"); end
blank?() click to toggle source

Strips out whitespace then tests if the string is empty.

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

@return [Boolean]

# File lib/garcon/core_ext/string.rb, line 78
def blank?
  strip.empty?
end
blue() click to toggle source
# File lib/garcon/core_ext/string.rb, line 288
def blue;       colorize(self, "\e[0;34m"); end
bold() click to toggle source
# File lib/garcon/core_ext/string.rb, line 274
def bold;       colorize(self, "\e[1m");    end
bright_red() click to toggle source
# File lib/garcon/core_ext/string.rb, line 295
def bright_red; colorize(self, "\e[1;41m"); end
clear() click to toggle source
# File lib/garcon/core_ext/string.rb, line 271
def clear;      colorize(self, "\e[0m");    end
colorize(text, color_code) click to toggle source
# File lib/garcon/core_ext/string.rb, line 305
def colorize(text, color_code) "#{color_code}#{text}\e[0m" end
compress_lines(spaced = true) click to toggle source

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

@example

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

@param [Boolean] spaced (default=true)

Determines whether returned string has whitespace collapsed or removed

@return [String]

Receiver with whitespace (including newlines) replaced

@api public

# File lib/garcon/core_ext/string.rb, line 229
def compress_lines(spaced = true)
  split($/).map { |line| line.strip }.join(spaced ? ' ' : '')
end
concealed() click to toggle source
# File lib/garcon/core_ext/string.rb, line 279
def concealed;  colorize(self, "\e[8m");    end
contains?(str) click to toggle source

Search a text file for a matching string

@return [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

@api public

# 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
cream() click to toggle source
# File lib/garcon/core_ext/string.rb, line 287
def cream;      colorize(self, "\e[1;33m"); end
crypt(salt = nil) click to toggle source

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

# 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
cyan() click to toggle source
# File lib/garcon/core_ext/string.rb, line 292
def cyan;       colorize(self, "\e[0;36m"); end
cyan2() click to toggle source
# File lib/garcon/core_ext/string.rb, line 293
def cyan2;      colorize(self, "\e[1;36m"); end
dark() click to toggle source
# File lib/garcon/core_ext/string.rb, line 275
def dark;       colorize(self, "\e[2m");    end
erase_char() click to toggle source
# File lib/garcon/core_ext/string.rb, line 273
def erase_char; colorize(self, "\e[P");     end
erase_line() click to toggle source
# File lib/garcon/core_ext/string.rb, line 272
def erase_line; colorize(self, "\e[K");     end
escape_regexp() click to toggle source

Escape all regexp special characters.

@example

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

@return [String]

Receiver with all regexp special characters escaped.

@api public

# File lib/garcon/core_ext/string.rb, line 137
def escape_regexp
  Regexp.escape self
end
flush() click to toggle source

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.

@example Remove leading whitespace and flush

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

@return [String]

@api public

# File lib/garcon/core_ext/string.rb, line 124
def flush
  gsub(/^#{self[/\A\s*/]}/, '').chomp
end
gray() click to toggle source
# File lib/garcon/core_ext/string.rb, line 281
def gray;       colorize(self, "\e[1;30m"); end
green() click to toggle source
# File lib/garcon/core_ext/string.rb, line 284
def green;      colorize(self, "\e[0;32m"); end
light_gray() click to toggle source
# File lib/garcon/core_ext/string.rb, line 294
def light_gray; colorize(self, "\e[2;37m"); end
magenta() click to toggle source
# File lib/garcon/core_ext/string.rb, line 283
def magenta;    colorize(self, "\e[1;31m"); end
margin(indicator = nil) click to toggle source

Remove whitespace margin.

@return [String]

Receiver with whitespace margin removed.

@api public

# 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
mustard() click to toggle source
# File lib/garcon/core_ext/string.rb, line 291
def mustard;    colorize(self, "\e[1;35m"); end
object_state(data = nil) click to toggle source

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

# File lib/garcon/core_ext/string.rb, line 24
def object_state(data = nil)
  data ? replace(data) : dup
end
olive() click to toggle source
# File lib/garcon/core_ext/string.rb, line 285
def olive;      colorize(self, "\e[1;32m"); end
on_black() click to toggle source
# File lib/garcon/core_ext/string.rb, line 297
def on_black;   colorize(self, "\e[40m");   end
on_blue() click to toggle source
# File lib/garcon/core_ext/string.rb, line 301
def on_blue;    colorize(self, "\e[44m");   end
on_cyan() click to toggle source
# File lib/garcon/core_ext/string.rb, line 303
def on_cyan;    colorize(self, "\e[46m");   end
on_green() click to toggle source
# File lib/garcon/core_ext/string.rb, line 299
def on_green;   colorize(self, "\e[42m");   end
on_magenta() click to toggle source
# File lib/garcon/core_ext/string.rb, line 302
def on_magenta; colorize(self, "\e[45m");   end
on_red() click to toggle source
# File lib/garcon/core_ext/string.rb, line 298
def on_red;     colorize(self, "\e[41m");   end
on_white() click to toggle source
# File lib/garcon/core_ext/string.rb, line 304
def on_white;   colorize(self, "\e[47m");   end
on_yellow() click to toggle source
# File lib/garcon/core_ext/string.rb, line 300
def on_yellow;  colorize(self, "\e[43m");   end
orange() click to toggle source
# File lib/garcon/core_ext/string.rb, line 290
def orange;     colorize(self, "\e[0;35m"); end
purple() click to toggle source
# File lib/garcon/core_ext/string.rb, line 289
def purple;     colorize(self, "\e[1;34m"); end
red() click to toggle source
# File lib/garcon/core_ext/string.rb, line 282
def red;        colorize(self, "\e[0;31m"); end
relative_path_from(other) click to toggle source

Calculate a relative path from other.

@example

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

@param [String] other

Base path to calculate *from*.

@return [String]

Relative path from _other_ to receiver.

@api public

# 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
reverse() click to toggle source
# File lib/garcon/core_ext/string.rb, line 278
def reverse;    colorize(self, "\e[7m");    end
shatter(re) click to toggle source

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

@example

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>"
  ]

@param [Regexp] regex

Regular expression for breaking string into array.

@return [String]

@api public

# 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) click to toggle source

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

@example

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

@param [#to_s] values

A list of values to translate and interpolate into receiver

@return [String]

Receiver translated with values translated and interpolated positionally

@api public

# 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_path() click to toggle source

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

@example

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

@return [String]

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

@api public

# File lib/garcon/core_ext/string.rb, line 177
def to_const_path
  snake_case.gsub(/::/, "/")
end
to_const_string() click to toggle source

Convert a path string to a constant name.

@example

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

@return [String]

Receiver converted to a constant name.

@api public

# File lib/garcon/core_ext/string.rb, line 163
def to_const_string
  gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
end
to_re(esc = false) click to toggle source

Turns a string into a regular expression.

"a?".to_re  #=> /a?/
# 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) click to toggle source

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

"[".to_rx  #=> /\[/
# File lib/garcon/core_ext/string.rb, line 66
def to_rx(esc = true)
  Regexp.new((esc ? Regexp.escape(self) : self))
end
underline() click to toggle source
# File lib/garcon/core_ext/string.rb, line 276
def underline;  colorize(self, "\e[4m");    end
unescape_regexp() click to toggle source

Unescape all regexp special characters.

@example

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

@return [String]

Receiver with all regexp special characters unescaped.

@api public

# File lib/garcon/core_ext/string.rb, line 150
def unescape_regexp
  self.gsub(/\\([\.\?\|\(\)\[\]\{\}\^\$\*\+\-])/, '\1')
end
white() click to toggle source
# File lib/garcon/core_ext/string.rb, line 296
def white;      colorize(self, "\e[0;97m"); end
yellow() click to toggle source
# File lib/garcon/core_ext/string.rb, line 286
def yellow;     colorize(self, "\e[0;33m"); end