| ... | ... |
@@ -161,3 +161,39 @@ module Helpers |
| 161 | 161 |
end |
| 162 | 162 |
end |
| 163 | 163 |
|
| 164 |
+class String |
|
| 165 |
+ def titlecase |
|
| 166 |
+ small_words = %w(a an and as at but by en for if in of on or the to v v. via vs vs.) |
|
| 167 |
+ |
|
| 168 |
+ x = split(" ").map do |word|
|
|
| 169 |
+ # note: word could contain non-word characters! |
|
| 170 |
+ # downcase all small_words, capitalize the rest |
|
| 171 |
+ small_words.include?(word.gsub(/\W/, "").downcase) ? word.downcase! : word.smart_capitalize! |
|
| 172 |
+ word |
|
| 173 |
+ end |
|
| 174 |
+ # capitalize first and last words |
|
| 175 |
+ x.first.to_s.smart_capitalize! |
|
| 176 |
+ x.last.to_s.smart_capitalize! |
|
| 177 |
+ # small words after colons are capitalized |
|
| 178 |
+ x.join(" ").gsub(/:\s?(\W*#{small_words.join("|")}\W*)\s/) { ": #{$1.smart_capitalize} " }
|
|
| 179 |
+ end |
|
| 180 |
+ |
|
| 181 |
+ def titlecase! |
|
| 182 |
+ replace(titlecase) |
|
| 183 |
+ end |
|
| 184 |
+ |
|
| 185 |
+ def smart_capitalize |
|
| 186 |
+ # ignore any leading crazy characters and capitalize the first real character |
|
| 187 |
+ if self =~ /^['"\(\[']*([a-z])/ |
|
| 188 |
+ i = index($1) |
|
| 189 |
+ x = self[i,self.length] |
|
| 190 |
+ # word with capitals and periods mid-word are left alone |
|
| 191 |
+ self[i,1] = self[i,1].upcase unless x =~ /[A-Z]/ or x =~ /\.\w+/ |
|
| 192 |
+ end |
|
| 193 |
+ self |
|
| 194 |
+ end |
|
| 195 |
+ |
|
| 196 |
+ def smart_capitalize! |
|
| 197 |
+ replace(smart_capitalize) |
|
| 198 |
+ end |
|
| 199 |
+end |
|
| 164 | 200 |
\ No newline at end of file |