Sha256: a61c56960e8825d0ce05b93d5ca63a7994ba35866af86beb7cbeb712a85e2dbe

Contents?: true

Size: 1.15 KB

Versions: 17

Compression:

Stored size: 1.15 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
    target = dup
    # ignore any leading crazy characters and capitalize the first real character
    if target =~ /^['"\(\[']*([a-z])/
      i = index($1)
      x = target[i,target.length]
      # word with capitals and periods mid-word are left alone
      target[i,1] = target[i,1].upcase unless x =~ /[A-Z]/ or x =~ /\.\w+/
    end
    target
  end

  def smart_capitalize!
    replace(smart_capitalize)
  end
end

Version data entries

17 entries across 17 versions & 2 rubygems

Version Path
octopress-3.0.0.rc.10 lib/octopress/ext/titlecase.rb
octopress-3.0.0.rc.9 lib/octopress/ext/titlecase.rb
octopress-3.0.0.rc.8 lib/octopress/ext/titlecase.rb
octopress-ink-1.0.0.alpha.44 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.43 lib/octopress-ink/helpers/titlecase.rb
octopress-3.0.0.rc.7 lib/octopress/ext/titlecase.rb
octopress-ink-1.0.0.alpha.42 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.41 lib/octopress-ink/helpers/titlecase.rb
octopress-3.0.0.rc.6 lib/octopress/ext/titlecase.rb
octopress-ink-1.0.0.alpha.40 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.39 lib/octopress-ink/helpers/titlecase.rb
octopress-ink-1.0.0.alpha.38 lib/octopress-ink/helpers/titlecase.rb
octopress-3.0.0.rc.5 lib/octopress/ext/titlecase.rb
octopress-3.0.0.rc.4 lib/octopress/ext/titlecase.rb
octopress-3.0.0.rc.3 lib/octopress/ext/titlecase.rb
octopress-3.0.0.rc.2 lib/octopress/ext/titlecase.rb
octopress-3.0.0.rc.1 lib/octopress/ext/titlecase.rb