Question

Is there any way to modify the titlecase method that comes with Rails so that it capitalizes everything it should but never takes anything that was already capitalized and makes it lowercase? E.g. The title "ABC photo shoot" should become "ABC Photo Shoot" and not "Abc Photo Shoot".

Was it helpful?

Solution

As I know there is no such built-in method in Rails. I just construct a custom one.

class String
  def smart_capitalize
    ws = self.split
    ws.each do |w|
      w.capitalize! unless w.match(/[A-Z]/)
    end
    ws.join(' ')    
  end
end

"ABC photo".smart_capitalize 
#=> "ABC Photo"

"iPad is made by Apple but not IBM".smart_capitalize
#=> "iPad Is Made By Apple But Not IBM"

Add: To exclude unimportant words as per Associated Press Style

class String
  def smart_capitalize
    ex = %w{a an and at but by for in nor of on or so the to up yet}
    ws = self.split
    ws.each do |w|
      unless w.match(/[A-Z]/) || ex.include?(w)
        w.capitalize! 
      end
    end
    ws.first.capitalize!
    ws.last.capitalize!
    ws.join(' ')    
  end
end

"a dog is not a cat".smart_capitalize
#=> "A Dog Is Not a Cat"

"Turn the iPad on".smart_capitalize
#=> "Turn the iPad On"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top