@@ -17,10 +17,16 @@ module Titleize
17
17
#
18
18
# "notes on a scandal" # => "Notes on a Scandal"
19
19
# "the good german" # => "The Good German"
20
- def titleize ( title )
20
+ def titleize ( title , opts = { } )
21
21
title = title . dup
22
22
title . downcase! unless title [ /[[:lower:]]/ ] # assume all-caps need fixing
23
23
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
+
24
30
phrases ( title ) . map do |phrase |
25
31
words = phrase . split
26
32
words . map . with_index do |word , index |
@@ -40,12 +46,14 @@ def word.capitalize
40
46
word
41
47
when /^[[:digit:]]/ # first character is a number
42
48
word
43
- when *( SMALL_WORDS + SMALL_WORDS . map { | small | small . capitalize } )
49
+ when *small_words
44
50
if index == 0 || index == words . size - 1
45
51
word . capitalize
46
52
else
47
53
word . downcase
48
54
end
55
+ when *acronyms
56
+ word . upcase
49
57
else
50
58
word . capitalize
51
59
end
@@ -91,13 +99,13 @@ def titleize(opts={})
91
99
if defined? ActiveSupport ::Inflector
92
100
ActiveSupport ::Inflector . titleize ( self , opts )
93
101
else
94
- Titleize . titleize ( self )
102
+ Titleize . titleize ( self , opts )
95
103
end
96
104
end
97
105
alias_method :titlecase , :titleize
98
106
99
- def titleize!
100
- replace ( titleize )
107
+ def titleize! ( opts = { } )
108
+ replace ( titleize ( opts ) )
101
109
end
102
110
alias_method :titlecase! , :titleize!
103
111
end
@@ -114,7 +122,7 @@ module ActiveSupport::Inflector
114
122
# This replaces the default Rails titleize. Like the default, it uses
115
123
# Inflector.underscore and Inflector.humanize to convert
116
124
# 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.
118
126
# This can be useful when dealing with words like "iPod" and "GPS".
119
127
#
120
128
# titleize is also aliased as titlecase.
@@ -126,7 +134,13 @@ def titleize(title, opts={})
126
134
title = ActiveSupport ::Inflector . underscore ( title ) if opts [ :underscore ]
127
135
title = ActiveSupport ::Inflector . humanize ( title ) if opts [ :humanize ]
128
136
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 )
130
144
end
131
145
alias_method :titlecase , :titleize
132
146
end
0 commit comments