Class: String

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.random(size = 8) ⇒ Object


105
106
107
# File 'lib/fat_core/string.rb', line 105

def self.random(size = 8)
  "abcdefghijklmnopqrstuvwxyz".split('').shuffle[0..size].join('')
end

Instance Method Details

#as_stringObject


68
69
70
# File 'lib/fat_core/string.rb', line 68

def as_string
  self
end

#as_symObject

Convert to symbol “Hello World” -> :hello_world


64
65
66
# File 'lib/fat_core/string.rb', line 64

def as_sym
  strip.squeeze(' ').gsub(/\s+/, '_').downcase.to_sym
end

#colorize(text, color_code) ⇒ Object


183
# File 'lib/fat_core/string.rb', line 183

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

181
# File 'lib/fat_core/string.rb', line 181

def console_blink;        colorize(self, "\001\e[5m\002");  end

#console_blueObject


175
# File 'lib/fat_core/string.rb', line 175

def console_blue;         colorize(self, "\001\e[1m\e[34m\002");  end

#console_boldObject


180
# File 'lib/fat_core/string.rb', line 180

def console_bold;         colorize(self, "\001\e[1m\002");  end

#console_dark_blueObject


176
# File 'lib/fat_core/string.rb', line 176

def console_dark_blue;    colorize(self, "\001\e[34m\002");       end

#console_dark_greenObject


172
# File 'lib/fat_core/string.rb', line 172

def console_dark_green;   colorize(self, "\001\e[32m\002");       end

#console_dark_redObject


170
# File 'lib/fat_core/string.rb', line 170

def console_dark_red;     colorize(self, "\001\e[31m\002");       end

#console_dark_yellowObject


174
# File 'lib/fat_core/string.rb', line 174

def console_dark_yellow;  colorize(self, "\001\e[33m\002");       end

#console_defObject


179
# File 'lib/fat_core/string.rb', line 179

def console_def;          colorize(self, "\001\e[1m\002");  end

#console_greenObject


171
# File 'lib/fat_core/string.rb', line 171

def console_green;        colorize(self, "\001\e[1m\e[32m\002");  end

#console_purpleObject


177
# File 'lib/fat_core/string.rb', line 177

def console_purple;       colorize(self, "\001\e[1m\e[35m\002");  end

#console_redObject

Thanks to Eugene at stackoverflow for the following. stackoverflow.com/questions/8806643/

colorized-output-breaks-linewrapping-with-readline

These color strings without confusing readline about the length of the prompt string in the shell. (Unlike the rainbow routines)


169
# File 'lib/fat_core/string.rb', line 169

def console_red;          colorize(self, "\001\e[1m\e[31m\002");  end

#console_yellowObject


173
# File 'lib/fat_core/string.rb', line 173

def console_yellow;       colorize(self, "\001\e[1m\e[33m\002");  end

#digdate2isoObject

Convert a string with an all-digit date to an iso string E.g., “20090923” -> “2009-09-23”


111
112
113
# File 'lib/fat_core/string.rb', line 111

def digdate2iso
  self.sub(/(\d\d\d\d)(\d\d)(\d\d)/, '\1-\2-\3')
end

#entitleObject


160
161
162
# File 'lib/fat_core/string.rb', line 160

def entitle
  self.dup.entitle!
end

#entitle!Object


115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/fat_core/string.rb', line 115

def entitle!
  little_words = %w[ a an the and or in on under of from as by to ]
  newwords = []
  words = split(/\s+/)
  first_word = true
  num_words = words.length
  words.each_with_index do |w, k|
    last_word = (k + 1 == num_words)
    if w =~ %r[c/o]i
      # Care of
      newwords.push("c/o")
    elsif w =~ %r[^p\.?o\.?$]i
      # Post office
      newwords.push("P.O.")
    elsif w =~ %r[^[0-9]+(st|nd|rd|th)$]i
      # Ordinals
      newwords.push(w.downcase)
    elsif w =~ %r[^(cr|dr|st|rd|ave|pk|cir)$]i
      # Common abbrs to capitalize
      newwords.push(w.capitalize)
    elsif w =~ %r[^(us|ne|se|rr)$]i
      # Common 2-letter abbrs to upcase
      newwords.push(w.upcase)
    elsif w =~ %r[^[0-9].*$]i
      # Other runs starting with numbers,
      # like 3-A
      newwords.push(w.upcase)
    elsif w =~ %r[^[^aeiouy]*$]i
      # All consonants, probably abbr
      newwords.push(w.upcase)
    elsif w =~ %r[^(\w+)-(\w+)$]i
      # Hypenated double word
      newwords.push($1.capitalize + '-' + $2.capitalize)
    elsif little_words.include?(w.downcase)
      # Only capitalize at beginning or end
      newwords.push((first_word or last_word) ? w.capitalize : w.downcase)
    else
      # All else
      newwords.push(w.capitalize)
    end
    first_word = false
  end
  self[0..-1] = newwords.join(' ')
end

#fuzzy_match(other) ⇒ Object

See if self contains colon- or space-separated words that include the colon- or space-separated words of other. Return the matched portion of self. Other cannot be a regex embedded in a string.


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/fat_core/string.rb', line 5

def fuzzy_match(other)
  # Remove periods, commas, and apostrophes
  other = other.gsub(/[.,']/, '')
  target = self.gsub(/[.,']/, '')
  matched_text = nil
  matchers = other.split(/[: ]+/)
  regexp_string = matchers.map {|m| ".*?#{Regexp.escape(m)}.*?"}.join('[: ]')
  regexp_string.sub!(/^\.\*\?/, '')
  regexp_string.sub!(/\.\*\?$/, '')
  regexp = /#{regexp_string}/i
  if match = regexp.match(target)
    matched_text = match[0]
  else
    matched_text = nil
  end
  matched_text
end

#matches_with(str) ⇒ Object

Here are instance methods for the class that includes Matchable This tries to convert the receiver object into a string, then matches against the given matcher, either via regex or a fuzzy string matcher.


27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/fat_core/string.rb', line 27

def matches_with(str)
  if str.nil?
    nil
  elsif str =~ /^\s*\//
    re = str.to_regexp
    if self.to_s =~ re
      $&
    else
      nil
    end
  else
    self.to_s.fuzzy_match(str)
  end
end

#tex_quoteObject


90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/fat_core/string.rb', line 90

def tex_quote
  r = self.dup
  r = r.gsub(/[{]/, 'XzXzXobXzXzX')
  r = r.gsub(/[}]/, 'XzXzXcbXzXzX')
  r = r.gsub(/\\/, '\textbackslash{}')
  r = r.gsub(/\^/, '\textasciicircum{}')
  r = r.gsub(/~/, '\textasciitilde{}')
  r = r.gsub(/\|/, '\textbar{}')
  r = r.gsub(/\</, '\textless{}')
  r = r.gsub(/\>/, '\textgreater{}')
  r = r.gsub(/([_$&%#])/) { |m| '\\' + m }
  r = r.gsub('XzXzXobXzXzX', '\\{')
  r = r.gsub('XzXzXcbXzXzX', '\\}')
end

#to_regexpObject

Convert a string of the form ‘/…/Iixm’ to a regular expression. However, make the regular expression case-insensitive by default and extend the modifier syntax to allow ‘/I’ to indicate case-sensitive.


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fat_core/string.rb', line 45

def to_regexp
  if self =~ /^\s*\/([^\/]*)\/([Iixm]*)\s*$/
    body = $1
    opts = $2
    flags = Regexp::IGNORECASE
    unless opts.blank?
      flags = 0 if opts.include?('I')
      flags |= Regexp::IGNORECASE if opts.include?('i')
      flags |= Regexp::EXTENDED if opts.include?('x')
      flags |= Regexp::MULTILINE if opts.include?('m')
    end
    flags = nil if flags == 0
    Regexp.new(body, flags)
  else
    Regexp.new(self)
  end
end

#wrap(width = 70, hang = 0) ⇒ Object


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/fat_core/string.rb', line 72

def wrap(width=70, hang=0)
  offset = 0
  trip = 1
  result = ''
  while (s = slice(offset, width))
    offset += width
    if trip == 1
      width -= hang
    else
      s = (' ' * hang) + s
    end
    result << s + "\n"
    trip += 1
  end
  # Remove the final newline before exiting
  result.strip
end