@@ -17,10 +17,16 @@ module Titleize
1717 #
1818 # "notes on a scandal" # => "Notes on a Scandal"
1919 # "the good german" # => "The Good German"
20- def titleize ( title )
20+ def titleize ( title , opts = { } )
2121 title = title . dup
2222 title . downcase! unless title [ /[[:lower:]]/ ] # assume all-caps need fixing
2323
24+ small_words = SMALL_WORDS + ( opts [ :small_words ] || [ ] )
25+ small_words = small_words + small_words . map { |small | small . capitalize }
26+
27+ acronyms = opts [ :acronyms ] || [ ]
28+ acronyms = acronyms + acronyms . map { |acronym | acronym . downcase }
29+
2430 phrases ( title ) . map do |phrase |
2531 words = phrase . split
2632 words . map . with_index do |word , index |
@@ -40,12 +46,14 @@ def word.capitalize
4046 word
4147 when /^[[:digit:]]/ # first character is a number
4248 word
43- when *( SMALL_WORDS + SMALL_WORDS . map { | small | small . capitalize } )
49+ when *small_words
4450 if index == 0 || index == words . size - 1
4551 word . capitalize
4652 else
4753 word . downcase
4854 end
55+ when *acronyms
56+ word . upcase
4957 else
5058 word . capitalize
5159 end
@@ -91,13 +99,13 @@ def titleize(opts={})
9199 if defined? ActiveSupport ::Inflector
92100 ActiveSupport ::Inflector . titleize ( self , opts )
93101 else
94- Titleize . titleize ( self )
102+ Titleize . titleize ( self , opts )
95103 end
96104 end
97105 alias_method :titlecase , :titleize
98106
99- def titleize!
100- replace ( titleize )
107+ def titleize! ( opts = { } )
108+ replace ( titleize ( opts ) )
101109 end
102110 alias_method :titlecase! , :titleize!
103111end
@@ -114,7 +122,7 @@ module ActiveSupport::Inflector
114122 # This replaces the default Rails titleize. Like the default, it uses
115123 # Inflector.underscore and Inflector.humanize to convert
116124 # underscored_names and CamelCaseNames to a more human form. However, you can change
117- # this behavior by passing :humanize => false or :underscore => false as options.
125+ # this behavior by passing :humanize => false or :underscore => false as options.
118126 # This can be useful when dealing with words like "iPod" and "GPS".
119127 #
120128 # titleize is also aliased as titlecase.
@@ -126,7 +134,13 @@ def titleize(title, opts={})
126134 title = ActiveSupport ::Inflector . underscore ( title ) if opts [ :underscore ]
127135 title = ActiveSupport ::Inflector . humanize ( title ) if opts [ :humanize ]
128136
129- Titleize . titleize ( title )
137+ # prioritize passed-in acronyms, fall back to those configured
138+ # for ActiveSupport::Inflector
139+ opts [ :acronyms ] ||= ActiveSupport ::Inflector . inflections . acronyms
140+
141+ passthru_opts = opts . select { |k , _ | [ :acronyms , :small_words ] . include? ( k ) }
142+
143+ Titleize . titleize ( title , passthru_opts )
130144 end
131145 alias_method :titlecase , :titleize
132146 end
0 commit comments