Class: String

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

Constant Summary collapse

ANSI_CLEAR =

Embed in a String to clear all previous ANSI sequences.

"\e[0m"
ANSI_BOLD =
"\e[1m"
ANSI_UNDERLINE =
"\e[4m"
BLACK =

Colors

"\e[30m"
RED =
"\e[31m"
GREEN =
"\e[32m"
YELLOW =
"\e[33m"
BLUE =
"\e[34m"
MAGENTA =
"\e[35m"
CYAN =
"\e[36m"
WHITE =
"\e[37m"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.natcmp(str1, str2) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/string_tools/core_ext/string.rb', line 43

def self.natcmp(str1, str2)
  str1, str2 = str1.dup, str2.dup
  compare_expression = /^(\D*)((?:\d+(?:\.\d+)?)*)(.*)$/

  # Remove all whitespace
  str1.gsub!(/\s*/, '')
  str2.gsub!(/\s*/, '')

  while (str1.length > 0) or (str2.length > 0)
    # Extract non-digits, digits and rest of string
    str1 =~ compare_expression
    chars1, num1, str1 = $1.dup, $2.dup, $3.dup

    str2 =~ compare_expression
    chars2, num2, str2 = $1.dup, $2.dup, $3.dup

    # Compare the non-digits
    case (chars1 <=> chars2)
    when 0 # Non-digits are the same, compare the digits...
      # If either number begins with a zero, then compare alphabetically,
      # otherwise compare numerically
      if !(num1[0] == 48 && num1[1] != 46) and !(num2[0] == 48 && num2[1] != 46)
        num1, num2 = num1.to_f, num2.to_f
      end

      case (num1 <=> num2)
      when -1 then return -1
      when 1 then return 1
      end
    when -1 then return -1
    when 1 then return 1
    end # case

  end # while

  # Strings are naturally equal
  0
end

Instance Method Details

#boldObject

Synopsys

Make text bolder (for ASCII terminals)


135
136
137
# File 'lib/string_tools/core_ext/string.rb', line 135

def bold
  surround_with_ansi(ANSI_BOLD)
end

#colorize(color, bold_or_options = nil) ⇒ Object

Synopsys

Colorize string (for terminals)
Does not work with sprintf yet

Usage

"ln -s".colorize(:red)

Args

+color+ - symbol, one of the following (black, white, red, green, yellow, blue, magenta, cyan)
+bold_or_options+ - True/False or Hash


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/string_tools/core_ext/string.rb', line 112

def colorize(color, bold_or_options = nil)
  is_bold      = bold_or_options.is_a?(TrueClass)
  is_underline = false

  if bold_or_options.is_a?(Hash)
    is_bold    ||= bold_or_options[:bold]
    is_underline = bold_or_options[:underline]
  end

  raise ArgumentError('Color must be a symbol') unless color.is_a?(Symbol)
  color_const = color.to_s.upcase.to_sym

  raise ArgumentError('Unknown color') unless self.class.const_defined?(color_const)
  ascii_color = self.class.const_get(color_const)

  s = surround_with_ansi(ascii_color)
  s = s.bold      if is_bold
  s = s.underline if is_underline
  s
end

#detect_encodingObject

shorthand



158
159
160
161
162
# File 'lib/string_tools/core_ext/string.rb', line 158

def detect_encoding
  e = ::CharDet.detect(self)["encoding"]
  e = 'windows-1251' if StringTools.cp1251_compatible_encodings.include?(e)
  e
end

#mb_downcaseObject



196
197
198
199
200
201
202
203
# File 'lib/string_tools/core_ext/string.rb', line 196

def mb_downcase
  # https://github.com/rails/rails/commit/393e19e508a08ede0f5037bccb984e3eb252d579
  if ActiveSupport::VERSION::STRING >= '4.0.0' && ActiveSupport::VERSION::STRING <= '4.2.0'
    ActiveSupport::Multibyte::Unicode.send(:database).codepoints
  end

  mb_chars.downcase.to_s
end

#naturalizedObject



39
40
41
# File 'lib/string_tools/core_ext/string.rb', line 39

def naturalized
  scan(/[^\d\.]+|[\d\.]+/).map{|f| f.match(/^\d+(\.\d+)?$/) ? f.to_f : f }
end

#remove_colorsObject

Synopsys

remove colors from colorized string


147
148
149
# File 'lib/string_tools/core_ext/string.rb', line 147

def remove_colors
  gsub(/\e\[\d+m/, '')
end

#remove_nonprintableObject

Public: returns copy of string with all non-printable characters removed

Examples

"q\uFFFEw\uFFFFe\uFFF0r\uFDD0t\uFDEFy".remove_nonprintable
# => "qwerty"

Returns String



213
214
215
# File 'lib/string_tools/core_ext/string.rb', line 213

def remove_nonprintable
  gsub(/[^[:print:]\n\t]/i, '')
end

#remove_nonprintable!Object

Public: removes all non-printable characters from string

Examples

"q\uFFFEw\uFFFFe\uFFF0r\uFDD0t\uFDEFy".remove_nonprintable!
# => "qwerty"

Returns String



225
226
227
# File 'lib/string_tools/core_ext/string.rb', line 225

def remove_nonprintable!
  replace(remove_nonprintable)
end

#strip_tagsObject

возвращает строку из которой удалены HTML-теги символы <>&“ остаются без изменения



20
21
22
# File 'lib/string_tools/core_ext/string.rb', line 20

def strip_tags
  ActionController::Base.helpers.strip_tags(self).to_str.gsub(/<!--/, '<--')
end

#to_bObject



31
32
33
# File 'lib/string_tools/core_ext/string.rb', line 31

def to_b
  StringTools::String.new(self).to_b
end

#to_cp1251Object



186
187
188
189
190
# File 'lib/string_tools/core_ext/string.rb', line 186

def to_cp1251
  encode 'cp1251', :undef => :replace, :invalid => :replace
rescue
  ''
end

#to_cp1251!Object



192
193
194
# File 'lib/string_tools/core_ext/string.rb', line 192

def to_cp1251!
  self.replace(self.to_cp1251)
end

#to_f_with_strip_commaObject

‘11,3’.to_f

> 11.3



26
27
28
# File 'lib/string_tools/core_ext/string.rb', line 26

def to_f_with_strip_comma
  self.gsub(/,/,'.').to_f_without_strip_comma
end

#to_punycodeObject

Выполняет преобразование строки в punycode.



83
84
85
# File 'lib/string_tools/core_ext/string.rb', line 83

def to_punycode
  Addressable::URI.parse(self).normalize.to_s
end

#to_script_safe_jsonObject



35
36
37
# File 'lib/string_tools/core_ext/string.rb', line 35

def to_script_safe_json
  self.to_json.gsub('</script>', '</" + "script>" + "')
end

#to_utf8Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/string_tools/core_ext/string.rb', line 168

def to_utf8
  # и так utf
  return self if is_utf8?

  enc = detect_encoding

  # если utf или английские буквы, то тоже ок
  return self if ['utf-8', 'ascii'].include?(enc)

  # если неизвестная каша, то возвращаем пустую строку
  return '' if enc.nil?

  # иначе пытаемся перекодировать
  encode 'utf-8', enc, :undef => :replace, :invalid => :replace
rescue
  ''
end

#to_utf8!Object



164
165
166
# File 'lib/string_tools/core_ext/string.rb', line 164

def to_utf8!
  self.replace(self.to_utf8)
end

#underlineObject

Synopsys

Make text underlined (for ASCII terminals)


141
142
143
# File 'lib/string_tools/core_ext/string.rb', line 141

def underline
  surround_with_ansi(ANSI_UNDERLINE)
end