Permalink
Browse files

added titlize so posts created with rake tasks will have nice titles

  • Loading branch information...
imathis committed Dec 7, 2009
1 parent a6262dc commit 6a1a9a8bb8966cc83c3664830ce45a1907b4212a
Showing with 36 additions and 0 deletions.
  1. +36 −0 source/_helpers.rb
View
@@ -161,3 +161,39 @@ def style_amp(input)
end
end
+class String
+ def titlecase
+ small_words = %w(a an and as at but by en for if in of on or the to v v. via vs vs.)
+
+ x = split(" ").map do |word|
+ # note: word could contain non-word characters!
+ # downcase all small_words, capitalize the rest
+ small_words.include?(word.gsub(/\W/, "").downcase) ? word.downcase! : word.smart_capitalize!
+ word
+ end
+ # capitalize first and last words
+ x.first.to_s.smart_capitalize!
+ x.last.to_s.smart_capitalize!
+ # small words after colons are capitalized
+ x.join(" ").gsub(/:\s?(\W*#{small_words.join("|")}\W*)\s/) { ": #{$1.smart_capitalize} " }
+ end
+
+ def titlecase!
+ replace(titlecase)
+ end
+
+ def smart_capitalize
+ # ignore any leading crazy characters and capitalize the first real character
+ if self =~ /^['"\(\[']*([a-z])/
+ i = index($1)
+ x = self[i,self.length]
+ # word with capitals and periods mid-word are left alone
+ self[i,1] = self[i,1].upcase unless x =~ /[A-Z]/ or x =~ /\.\w+/
+ end
+ self
+ end
+
+ def smart_capitalize!
+ replace(smart_capitalize)
+ end
+end

0 comments on commit 6a1a9a8

Please sign in to comment.