Sha256: e7b5f87eff38f0a729afd4a54c9f3fa7e64bd69facef600911e9e19999438212

Contents?: true

Size: 1.12 KB

Versions: 29

Compression:

Stored size: 1.12 KB

Contents

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 are capitalized after colon, period, exclamation mark, question mark
    x.join(" ").gsub(/(:|\.|!|\?)\s?(\W*#{small_words.join("|")}\W*)\s/) { "#{$1} #{$2.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

Version data entries

29 entries across 29 versions & 3 rubygems

Version Path
jekyll-lenciel-theme-1.0.29 plugins/titlecase.rb
jekyll-lenciel-theme-1.0.28 plugins/titlecase.rb
octopress-ink-1.0.0.alpha.37 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.36 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.35 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.34 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.33 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.32 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.31 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.30 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.29 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.28 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.27 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.26 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.25 lib/octopress-ink/helpers/titlecase.rb
link-checker-0.7.2 spec/test-site/plugins/titlecase.rb
link-checker-0.7.1 spec/test-site/plugins/titlecase.rb
link-checker-0.6.0 spec/test-site/plugins/titlecase.rb
link-checker-0.5.2 spec/test-site/plugins/titlecase.rb
link-checker-0.5.1 spec/test-site/plugins/titlecase.rb