Class: String
Class Method Summary collapse
-
.pluralize_word(num, vals = ["is", "are"]) ⇒ Object
Returns “is” or “are” based on the number, i.e.
- .randomize(length = 10) ⇒ Object
Instance Method Summary collapse
-
#blank? ⇒ Boolean
If the string is empty, this will return true.
-
#breakify(every = 30) ⇒ Object
makes long strings of unbroken characters wrap inside elements (hopefully! tested in Safari, Firefox, and IE for Windows) For documentation about this kind of workaround to this browser compatibility problem please see the following URL’s: www.quirksmode.org/oddsandends/wbr.html krijnhoetmer.nl/stuff/css/word-wrap-break-word/ note: if the txt has spaces, this will only try to break up runs of non-space characters longer than “every” characters.
- #breakify!(every = 30) ⇒ Object
-
#camelcase ⇒ Object
Camel cases the string.
- #capitalize_all_words ⇒ Object
- #capitalize_all_words! ⇒ Object
-
#constantize ⇒ Object
Returns a constant of the string.
- #ends_with?(x) ⇒ Boolean
- #hexdigest ⇒ Object
- #hexdigest! ⇒ Object
- #linkify(enabled = true, options = {}, &block) ⇒ Object
- #methodize ⇒ Object
-
#plural ⇒ Object
Maps to Mack::Utils::Inflector.instance.pluralize.
- #remove(val) ⇒ Object
- #remove!(val) ⇒ Object
-
#singular ⇒ Object
Maps to Mack::Utils::Inflector.instance.singularize.
-
#sql_safe_str ⇒ Object
keep adding on to this whenever it becomes apparent that unsafe strings could get passed through into the database.
- #sql_safe_str! ⇒ Object
- #starts_with?(x) ⇒ Boolean
-
#to_instance ⇒ Object
See Class new_instance_of for more details.
- #truncate(length = 30, truncate_string = "...") ⇒ Object
- #truncate!(length = 30, truncate_string = "...") ⇒ Object
- #underscore ⇒ Object
-
#uri_escape ⇒ Object
Performs URI escaping so that you can construct proper query strings faster.
-
#uri_unescape ⇒ Object
Unescapes a URI escaped string.
Class Method Details
.pluralize_word(num, vals = ["is", "are"]) ⇒ Object
Returns “is” or “are” based on the number, i.e. “i=6; There #isare(i) #i topics here.”
170 171 172 173 |
# File 'lib/extensions/string.rb', line 170 def self.pluralize_word(num, vals = ["is", "are"]) return vals[0] if num.to_i==1 return vals[1] end |
.randomize(length = 10) ⇒ Object
224 225 226 227 228 229 |
# File 'lib/extensions/string.rb', line 224 def self.randomize(length = 10) chars = ("A".."H").to_a + ("J".."N").to_a + ("P".."T").to_a + ("W".."Z").to_a + ("3".."9").to_a newpass = "" 1.upto(length) { |i| newpass << chars[rand(chars.size-1)] } return newpass.upcase end |
Instance Method Details
#blank? ⇒ Boolean
If the string is empty, this will return true.
30 31 32 |
# File 'lib/extensions/string.rb', line 30 def blank? self == "" end |
#breakify(every = 30) ⇒ Object
makes long strings of unbroken characters wrap inside elements (hopefully! tested in Safari, Firefox, and IE for Windows) For documentation about this kind of workaround to this browser compatibility problem please see the following URL’s: www.quirksmode.org/oddsandends/wbr.html krijnhoetmer.nl/stuff/css/word-wrap-break-word/ note: if the txt has spaces, this will only try to break up runs of non-space characters longer than “every” characters
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/extensions/string.rb', line 188 def breakify(every = 30) every = 1 if every < 1 text = self textile_regex = /([^\"]+\"):([^:]*:[\/\/]{0,1}[^ ]*)/ long_regex = /\S{#{every},}/ brokentxt = text.gsub(long_regex) do |longword| if longword =~ textile_regex #if the longword is a textile link...ignore and recheck for the link text only textile_link = textile_regex.match(longword)[0] link_text = textile_regex.match(longword)[1] longword = link_text if longword =~ long_regex #link text is long...allow break textile_link.scan(/.{1,#{every}}/).join("<wbr/>") else textile_link #the url is what triggered the match...so leave it alone end else longword.scan(/.{1,#{every}}/).join("<wbr/>") #no textile link matched end end #text = %Q[<span style='word-wrap:break-word;wbr:after{content:"\\00200B"}'>#{brokentxt}</span>] #brokentxt.gsub("<wbr/>", "<br />") brokentxt.gsub("<wbr/>", " ") end |
#breakify!(every = 30) ⇒ Object
212 213 214 |
# File 'lib/extensions/string.rb', line 212 def breakify!(every = 30) self.replace(self.breakify(every)) end |
#camelcase ⇒ Object
Camel cases the string.
Examples:
"user".camelcase # => User
"my_blog".camelcase # => MyBlog
"my/blog".camelcase # => My::Blog
15 16 17 |
# File 'lib/extensions/string.rb', line 15 def camelcase self.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase } end |
#capitalize_all_words ⇒ Object
246 247 248 |
# File 'lib/extensions/string.rb', line 246 def capitalize_all_words self.gsub(/\b\w/) {|s| s.upcase} end |
#capitalize_all_words! ⇒ Object
250 251 252 |
# File 'lib/extensions/string.rb', line 250 def capitalize_all_words! self.replace(self.capitalize_all_words) end |
#constantize ⇒ Object
Returns a constant of the string.
Examples:
"User".constantize # => User
"HomeController".constantize # => HomeController
"Mack::Configuration" # => Mack::Configuration
25 26 27 |
# File 'lib/extensions/string.rb', line 25 def constantize Module.instance_eval("::#{self}") end |
#ends_with?(x) ⇒ Boolean
165 166 167 |
# File 'lib/extensions/string.rb', line 165 def ends_with?(x) self.match(/#{x}$/) ? true : false end |
#hexdigest ⇒ Object
216 217 218 |
# File 'lib/extensions/string.rb', line 216 def hexdigest Digest::SHA1.hexdigest(self.downcase) end |
#hexdigest! ⇒ Object
220 221 222 |
# File 'lib/extensions/string.rb', line 220 def hexdigest! self.replace(self.hexdigest) end |
#linkify(enabled = true, options = {}, &block) ⇒ Object
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 |
# File 'lib/extensions/string.rb', line 44 def linkify(enabled = true, = {}, &block) text = self.dup m = text.match(/\"([^"]+)\"\:([^:]+\:\S+)/) until m.nil? y = m.to_s t = m[1] url = m[2] # The code below handles punctuation or p tags being mistakenly added to the url when the link is at the end of a sentence or body url_punct_match = /\W*[ ]*[\<\/p\>]*$/.match(url) punct = '' if url_punct_match && url_punct_match[0] != "" url.chomp!(url_punct_match[0]) punct = url_punct_match[0] unless url_punct_match == "=" end if block_given? if enabled ret = yield t, url, text.gsub!(y, ret) else text.gsub!(y, t.to_s) end else if enabled text.gsub!(y, "<a href=\"#{url}\" #{.join("%s=\"%s\"", " ")}>#{t}</a>#{punct}")# punct places punctuation back into proper place else text.gsub!(y, t.to_s) end end m = text.match(/\"([^"]+)\"\:([^:]+\:\S+)/) end return text end |
#methodize ⇒ Object
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 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 |
# File 'lib/extensions/string.rb', line 79 def methodize x = self # if we get down to a nil or an empty string raise an exception! raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == '' # get rid of the big stuff in the front/back x.strip! # if we get down to a nil or an empty string raise an exception! raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == '' x = x.underscore # get rid of spaces and make the _ x.gsub!(' ', '_') # get rid of everything that isn't 'safe' a-z, 0-9, ?, !, =, _ x.gsub!(/([^ a-zA-Z0-9\_\?\!\=]+)/n, '_') # if we get down to a nil or an empty string raise an exception! raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == '' # condense multiple 'safe' non a-z chars to just one. # ie. ___ becomes _ !!!! becomes ! etc... [' ', '_', '?', '!', "="].each do |c| x.squeeze!(c) end # if we get down to a nil or an empty string raise an exception! raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == '' #down case the whole thing x.downcase! # get rid of any characters at the beginning that aren't a-z while !x.match(/^[a-z]/) x.slice!(0) # if we get down to a nil or an empty string raise an exception! raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == '' end # let's trim this bad boy down a bit now that we've cleaned it up, somewhat. # we should do this before cleaning up the end character, because it's possible to end up with a # bad char at the end if you trim too late. x = x[0..100] if x.length > 100 # get rid of any characters at the end that aren't safe while !x.match(/[a-z0-9\?\!\=]$/) x.slice!(x.length - 1) # if we get down to a nil or an empty string raise an exception! raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == '' end # if we get down to a nil or an empty string raise an exception! raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == '' # let's get rid of characters that don't belong in the 'middle' of the method. orig_middle = x[1..(x.length - 2)] n_middle = orig_middle.dup ['?', '!', "="].each do |c| n_middle.gsub!(c, "_") end # the previous gsub can leave us with multiple underscores that need cleaning up. n_middle.squeeze!("_") x.gsub!(orig_middle, n_middle) x.gsub!("_=", "=") x end |
#plural ⇒ Object
Maps to Mack::Utils::Inflector.instance.pluralize
35 36 37 |
# File 'lib/extensions/string.rb', line 35 def plural Mack::Utils::Inflector.instance.pluralize(self) end |
#remove(val) ⇒ Object
175 176 177 |
# File 'lib/extensions/string.rb', line 175 def remove(val) gsub(val, '') end |
#remove!(val) ⇒ Object
179 180 181 |
# File 'lib/extensions/string.rb', line 179 def remove!(val) gsub!(val, '') end |
#singular ⇒ Object
Maps to Mack::Utils::Inflector.instance.singularize
40 41 42 |
# File 'lib/extensions/string.rb', line 40 def singular Mack::Utils::Inflector.instance.singularize(self) end |
#sql_safe_str ⇒ Object
keep adding on to this whenever it becomes apparent that unsafe strings could get passed through into the database
256 257 258 259 260 |
# File 'lib/extensions/string.rb', line 256 def sql_safe_str if !self.nil? self.gsub(/[\']/, "\'\'") end end |
#sql_safe_str! ⇒ Object
262 263 264 |
# File 'lib/extensions/string.rb', line 262 def sql_safe_str! self.replace(self.sql_safe_str) end |
#starts_with?(x) ⇒ Boolean
161 162 163 |
# File 'lib/extensions/string.rb', line 161 def starts_with?(x) self.match(/^#{x}/) ? true : false end |
#to_instance ⇒ Object
See Class new_instance_of for more details.
5 6 7 |
# File 'lib/extensions/string.rb', line 5 def to_instance Class.new_instance_of(self) end |
#truncate(length = 30, truncate_string = "...") ⇒ Object
231 232 233 234 235 236 237 238 239 240 |
# File 'lib/extensions/string.rb', line 231 def truncate(length = 30, truncate_string = "...") if self.nil? then return end l = length - truncate_string.length if $KCODE == "NONE" self.length > length ? self[0...l] + truncate_string : self else chars = self.split(//) chars.length > length ? chars[0...l].join + truncate_string : self end end |
#truncate!(length = 30, truncate_string = "...") ⇒ Object
242 243 244 |
# File 'lib/extensions/string.rb', line 242 def truncate!(length = 30, truncate_string = "...") self.replace(self.truncate(length, truncate_string)) end |
#underscore ⇒ Object
152 153 154 155 156 157 158 159 |
# File 'lib/extensions/string.rb', line 152 def underscore camel_cased_word = self.dup camel_cased_word.to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end |
#uri_escape ⇒ Object
Performs URI escaping so that you can construct proper query strings faster. Use this rather than the cgi.rb version since it’s faster. (Stolen from Camping).
269 270 271 272 273 |
# File 'lib/extensions/string.rb', line 269 def uri_escape self.gsub(/([^ a-zA-Z0-9_.-]+)/n) { '%'+$1.unpack('H2'*$1.size).join('%').upcase }.tr(' ', '+') end |
#uri_unescape ⇒ Object
Unescapes a URI escaped string. (Stolen from Camping).
276 277 278 279 280 |
# File 'lib/extensions/string.rb', line 276 def uri_unescape self.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){ [$1.delete('%')].pack('H*') } end |