Module: TitleCase
- Included in:
- String
- Defined in:
- lib/droom/title_case.rb
Overview
Ruby Title Case A Ruby implementation of John Gruber’s Title Case daringfireball.net/2008/05/title_case
Copyright © Paul Mucur (mucur.name), 2008. Dual-licensed under the BSD (BSD-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
Constant Summary collapse
- SMALL_WORDS_RE =
A regular expression to match small words that should not be titleized.
/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v\.?|via|vs\.?)$/
Instance Method Summary collapse
Instance Method Details
#title_case ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/droom/title_case.rb', line 44 def title_case # Keep track when a colon has been used at the end of a word. colon_preceding = false # Split the string by any whitespace and then inspect each word # at a time. words = split(/\s+/).map do |word| title_cased_word = if colon_preceding # If there was a colon preceding this word then titleize # it even if it is a small word. colon_preceding = false titleize_if_appropriate(word) elsif word.downcase[SMALL_WORDS_RE] # If this is a small word, make it lowercase. word.downcase else # In all other cases, titleize the word. titleize_if_appropriate(word) end # If this word ends in a colon, set the flag so that the # following word can be titleized. colon_preceding = true if word[/:$/] title_cased_word end # Always capitalise the first and last words. words[0] = titleize_if_appropriate(words[0]) words[-1] = titleize_if_appropriate(words[-1]) words.join(" ") end |
#titleize_if_appropriate(word) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/droom/title_case.rb', line 27 def titleize_if_appropriate(word) if word # If a word does not contain a full-stop within itself and it doesn't # contain any capital letters apart from its first letter, titleize it. if !word[/\w\.\w/] && !word[/^.+[A-Z]/] # Capitalise the first *word* character (therefore avoiding problems # where the first character is some punctuation). word[/^\W*\w/] &&= word[/^\W*\w/].upcase end word else "" end end |