Rails只会向上标题

时间:2013-07-07 20:18:45

标签: ruby-on-rails-3 title-case

有没有办法修改Rails附带的titlecase方法,以便它可以大写它应该的所有内容但是从不需要任何已经大写的内容并使其小写?例如。标题“ABC照片拍摄”应该成为“ABC照片拍摄”而不是“Abc Photo Shoot”。

1 个答案:

答案 0 :(得分:1)

据我所知,Rails中没有这样的内置方法。我只是构建一个自定义的。

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"

添加:按照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"